commit_id
string
repo
string
commit_message
string
diff
string
label
int64
996a7849633a5aeb2b35665b346e7c4ca28bccb4
1up-lab/OneupUploaderBundle
Fixes scrutinizer-ci warnings. Do not test against: too_many_methods too_many_fields coupling_between_objects As this bundle provides a base Controller that is dependant on many coupled objects/interfaces, the coupling does not really make sense to test.
commit 996a7849633a5aeb2b35665b346e7c4ca28bccb4 Author: Jim Schmid <[email protected]> Date: Wed Oct 23 15:03:40 2013 +0200 Fixes scrutinizer-ci warnings. Do not test against: too_many_methods too_many_fields coupling_between_objects As this bundle provides a base Controller that is dependant on many coupled objects/interfaces, the coupling does not really make sense to test. diff --git a/.scrutinizer.yml b/.scrutinizer.yml index 764db5d..dc9dd29 100644 --- a/.scrutinizer.yml +++ b/.scrutinizer.yml @@ -1,6 +1,13 @@ tools: php_code_sniffer: true php_cs_fixer: true - php_mess_detector: true + php_mess_detector: + config: + code_size_rules: + too_many_fields: false + too_many_methods: false + + design_rules: + coupling_between_objects: false php_analyzer: true sensiolabs_security_checker: true \ No newline at end of file
0
d84b721e428a44bf3a3e888898689b46ae1675a1
1up-lab/OneupUploaderBundle
Added a FAQ entry.
commit d84b721e428a44bf3a3e888898689b46ae1675a1 Author: Jim Schmid <[email protected]> Date: Fri Apr 12 17:15:14 2013 +0200 Added a FAQ entry. diff --git a/Resources/doc/index.md b/Resources/doc/index.md index db17308..cb24aa1 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -117,6 +117,10 @@ some more advanced features. ## FAQ +> I want to use a frontend library you don't yet support + +This is absolutely no problem, just follow the instructions given in the corresponding [documentation file](custom_uploader.md). If you think that others could profit of your code, please consider making a pull request. I'm always happy for any kind of contribution. + > Why didn't you implement the _delete_ feature provided by Fine Uploader? FineUploaders _delete Feature_ is using generated unique names we would have to store in order to track down which file to delete. But both the storage and the deletetion of files are tight-coupled with the logic of your very own implementation. This means we leave the _delete Feature_ open for you to implement. Information on how the route must be crafted can be found on the [official documentation](https://github.com/Widen/fine-uploader/blob/master/docs/options-fineuploaderbasic.md#deletefile-option-properties) and on [the blog](http://blog.fineuploader.com/2013/01/delete-uploaded-file-in-33.html) of Fine Uploader.
0
12c37c7407cfc8d34e93ca3243f9e9f786180756
1up-lab/OneupUploaderBundle
travis test
commit 12c37c7407cfc8d34e93ca3243f9e9f786180756 Author: Martin Aarhof <[email protected]> Date: Wed Dec 9 19:29:04 2015 +0100 travis test diff --git a/.travis.yml b/.travis.yml index 5a3affa..f9fa7be 100644 --- a/.travis.yml +++ b/.travis.yml @@ -24,5 +24,6 @@ matrix: before_script: - composer selfupdate + - composer require symfony/http-kernel:${SYMFONY_VERSION} --prefer-source - composer require symfony/framework-bundle:${SYMFONY_VERSION} --prefer-source - composer install --dev --prefer-source
0
a1e93a4411a2a16b46a4d03f8e607bcee6ec54f5
1up-lab/OneupUploaderBundle
Dispatch a PostDeleteEvent after deleting an image.
commit a1e93a4411a2a16b46a4d03f8e607bcee6ec54f5 Author: Jim Schmid <[email protected]> Date: Thu Mar 14 20:07:04 2013 +0100 Dispatch a PostDeleteEvent after deleting an image. diff --git a/Controller/UploaderController.php b/Controller/UploaderController.php index a59fe54..affdd97 100644 --- a/Controller/UploaderController.php +++ b/Controller/UploaderController.php @@ -68,7 +68,12 @@ class UploaderController implements UploadControllerInterface if(is_null($uuid)) return new HttpException(400, 'You must provide a file uuid.'); - return $this->storage->remove($this->type, $uuid) ? + $result = $this->storage->remove($this->type, $uuid); + + $postUploadEvent = new PostUploadEvent($this->request, $uuid, $this->type); + $this->dispatcher->dispatch(UploadEvents::POST_UPLOAD, $postUploadEvent); + + return $result ? new JsonResponse(array('success' => true)): new JsonResponse(array('error' => 'An unknown error occured.')); } @@ -92,7 +97,7 @@ class UploaderController implements UploadControllerInterface throw new UploadException('This extension is not allowed.'); $name = $this->namer->name($file, $this->config['directory_prefix']); - + $postUploadEvent = new PostUploadEvent($file, $this->request, $this->type, array( 'use_orphanage' => $this->config['use_orphanage'], 'file_name' => $name, diff --git a/Event/PostDeleteEvent.php b/Event/PostDeleteEvent.php index 00f9a93..0528225 100644 --- a/Event/PostDeleteEvent.php +++ b/Event/PostDeleteEvent.php @@ -5,26 +5,17 @@ namespace Oneup\UploaderBundle\Event; use Symfony\Component\EventDispatcher\Event; use Symfony\Component\HttpFoundation\Request; -use Symfony\Component\HttpFoundation\File\File; - class PostDeleteEvent extends Event { - protected $file; - protected $request; + protected $requets; + protected $uuid; protected $type; - protected $options; - public function __construct(File $file, Request $request, $type, array $options = array()) + public function __construct(Request $request, $uuid, $type) { - $this->file = $file; $this->request = $request; + $this->uuid = $uuid; $this->type = $type; - $this->options = $options; - } - - public function getFile() - { - return $this->file; } public function getRequest() @@ -32,13 +23,13 @@ class PostDeleteEvent extends Event return $this->request; } - public function getType() + public function getUuid() { - return $this->type; + return $this->uuid; } - public function getOptions() + public function getType() { - return $this->options; + return $this->type; } } \ No newline at end of file
0
dad8de6070dd9d4fb54e00da12aa23d2e38c613b
1up-lab/OneupUploaderBundle
New depending.in image source.
commit dad8de6070dd9d4fb54e00da12aa23d2e38c613b Author: Jim Schmid <[email protected]> Date: Mon Nov 18 10:50:13 2013 +0100 New depending.in image source. diff --git a/README.md b/README.md index 0abe5c1..7ddeab2 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ Features included: * Fully unit tested [![Build Status](https://travis-ci.org/1up-lab/OneupUploaderBundle.png?branch=master)](https://travis-ci.org/1up-lab/OneupUploaderBundle) -[![Dependencies Status](https://d2xishtp1ojlk0.cloudfront.net/d/8654803)](http://depending.in/1up-lab/OneupUploaderBundle) +[![Dependencies Status](https://depending.in/1up-lab/OneupUploaderBundle.png)](http://depending.in/1up-lab/OneupUploaderBundle) [![Total Downloads](https://poser.pugx.org/oneup/uploader-bundle/d/total.png)](https://packagist.org/packages/oneup/uploader-bundle) Documentation
0
f19d7eb9d9bb2282b17504727eba1656a965ac76
1up-lab/OneupUploaderBundle
Introducing the new StorageLayer.
commit f19d7eb9d9bb2282b17504727eba1656a965ac76 Author: Jim Schmid <[email protected]> Date: Wed Mar 13 08:26:19 2013 +0100 Introducing the new StorageLayer. diff --git a/Controller/UploaderController.php b/Controller/UploaderController.php index e922323..631ce7e 100644 --- a/Controller/UploaderController.php +++ b/Controller/UploaderController.php @@ -3,9 +3,6 @@ namespace Oneup\UploaderBundle\Controller; use Symfony\Component\HttpFoundation\JsonResponse; -use Gaufrette\Stream\Local as LocalStream; -use Gaufrette\StreamMode; - use Oneup\UploaderBundle\Controller\UploadControllerInterface; class UploaderController implements UploadControllerInterface @@ -35,23 +32,11 @@ class UploaderController implements UploadControllerInterface foreach($files as $file) { + // get name and directory and put them together $name = $this->namer->name($file); - $path = $file->getPathname(); - - $src = new LocalStream($path); - $dst = $this->storage->createStream($name); - - $src->open(new StreamMode('rb+')); - $dst->open(new StreamMode('ab+')); - - while(!$src->eof()) - { - $data = $src->read(100000); - $written = $dst->write($data); - } + $name = sprintf('%s/%s', $this->config['directory_prefix'], $name); - $dst->close(); - $src->close(); + $this->storage->upload($file, $name); } return new JsonResponse(array('success' => true)); diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index bc4b949..2640c61 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -10,6 +10,8 @@ use Symfony\Component\DependencyInjection\Loader; class OneupUploaderExtension extends Extension { + protected static $storageServices = array(); + public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); @@ -42,11 +44,39 @@ class OneupUploaderExtension extends Extension $mapping['directory_prefix'] = $key; } + $mapping['storage'] = $this->registerStorageService($container, $mapping); $this->registerServicesPerMap($container, $key, $mapping); } } - public function registerServicesPerMap(ContainerBuilder $container, $type, $mapping) + protected function registerStorageService(ContainerBuilder $container, $mapping) + { + $storage = $mapping['storage']; + + // if service has already been declared, return + if(in_array($storage, self::$storageServices)) + return; + + // get base name of gaufrette storage + $name = explode('.', $storage); + $name = end($name); + + // create name of new storage service + $service = sprintf('oneup_uploader.storage.%s', $name); + + $container + ->register($service, $container->getParameter('oneup_uploader.storage.class')) + + // inject the actual gaufrette filesystem + ->addArgument(new Reference($storage)) + ; + + self::$storageServices[] = $name; + + return $service; + } + + protected function registerServicesPerMap(ContainerBuilder $container, $type, $mapping) { // create controllers based on mapping $container diff --git a/Resources/config/uploader.xml b/Resources/config/uploader.xml index 3816e43..b0e8de6 100644 --- a/Resources/config/uploader.xml +++ b/Resources/config/uploader.xml @@ -9,6 +9,7 @@ <parameter key="oneup_uploader.namer.uniqid.class">Oneup\UploaderBundle\Uploader\Naming\UniqidNamer</parameter> <parameter key="oneup_uploader.routing.loader.class">Oneup\UploaderBundle\Routing\RouteLoader</parameter> <parameter key="oneup_uploader.controller.class">Oneup\UploaderBundle\Controller\UploaderController</parameter> + <parameter key="oneup_uploader.storage.class">Oneup\UploaderBundle\Uploader\Storage\GaufretteStorage</parameter> </parameters> <services> diff --git a/Uploader/Storage/GaufretteStorage.php b/Uploader/Storage/GaufretteStorage.php new file mode 100644 index 0000000..a5fb5d8 --- /dev/null +++ b/Uploader/Storage/GaufretteStorage.php @@ -0,0 +1,52 @@ +<?php + +namespace Oneup\UploaderBundle\Uploader\Storage; + +use Symfony\Component\HttpFoundation\File\File; +use Gaufrette\Stream\Local as LocalStream; +use Gaufrette\StreamMode; +use Gaufrette\Filesystem; +use Oneup\UploaderBundle\Uploader\Storage\StorageInterface; + +class GaufretteStorage implements StorageInterface +{ + protected $filesystem; + + public function __construct(Filesystem $filesystem) + { + $this->filesystem = $filesystem; + } + + public function upload(File $file, $name) + { + $path = $file->getPathname(); + + $src = new LocalStream($path); + $dst = $this->filesystem->createStream($name); + + // this is a somehow ugly workaround introduced + // because the stream-mode is not able to create + // subdirectories, while "write" does. + if(!$this->filesystem->has($name)) + $this->filesystem->write($name, '', true); + + $src->open(new StreamMode('rb+')); + $dst->open(new StreamMode('ab+')); + + while(!$src->eof()) + { + $data = $src->read(100000); + $written = $dst->write($data); + } + + $dst->close(); + $src->close(); + + return true; + } + + public function remove(File $file) + { + + } +} \ No newline at end of file diff --git a/Uploader/Storage/StorageInterface.php b/Uploader/Storage/StorageInterface.php new file mode 100644 index 0000000..1e4a287 --- /dev/null +++ b/Uploader/Storage/StorageInterface.php @@ -0,0 +1,11 @@ +<?php + +namespace Oneup\UploaderBundle\Uploader\Storage; + +use Symfony\Component\HttpFoundation\File\File; + +interface StorageInterface +{ + public function upload(File $file, $name); + public function remove(File $file); +} \ No newline at end of file
0
7f0f7b112a36f27ab0cb18368698bf74b65f1967
1up-lab/OneupUploaderBundle
Merge branch 'master' into feature/symfony3-support
commit 7f0f7b112a36f27ab0cb18368698bf74b65f1967 (from 5cb66bed0c0aa9f889ad767944de0ed74357e564) Merge: 5cb66be 774c82d Author: David Greminger <[email protected]> Date: Tue Sep 19 12:55:12 2017 +0200 Merge branch 'master' into feature/symfony3-support diff --git a/.travis.yml b/.travis.yml index 537eef5..cd37eb1 100644 --- a/.travis.yml +++ b/.travis.yml @@ -22,9 +22,27 @@ matrix: allow_failures: - env: SYMFONY_VERSION=dev-master -before_script: + include: + - php: 5.6 + env: SYMFONY_VERSION=2.4.* + - php: 5.6 + env: SYMFONY_VERSION=2.5.* + - php: 5.6 + env: SYMFONY_VERSION=2.6.* + - php: 5.6 + env: SYMFONY_VERSION=2.7.* + - php: 5.6 + env: SYMFONY_VERSION=2.8.* + - php: 5.6 + env: SYMFONY_VERSION=3.0.* + - php: 5.6 + env: SYMFONY_VERSION=dev-master + +before_install: - composer selfupdate - - composer require symfony/http-kernel:${SYMFONY_VERSION} --prefer-source - - composer install --dev --prefer-source + +before_script: + - travis_wait composer require symfony/framework-bundle:${SYMFONY_VERSION} --prefer-source + - travis_wait composer install --dev --prefer-source script: ./vendor/bin/phpunit diff --git a/Tests/Uploader/Storage/FlysystemStorageTest.php b/Tests/Uploader/Storage/FlysystemStorageTest.php index bdd43e9..121a7ec 100644 --- a/Tests/Uploader/Storage/FlysystemStorageTest.php +++ b/Tests/Uploader/Storage/FlysystemStorageTest.php @@ -53,6 +53,22 @@ class FlysystemStorageTest extends \PHPUnit_Framework_TestCase } } + public function testUploadWithPath() + { + $payload = new FilesystemFile(new UploadedFile($this->file, 'grumpycat.jpeg', null, null, null, true)); + $this->storage->upload($payload, 'notsogrumpyanymore.jpeg', 'cat'); + + $finder = new Finder(); + $finder->in($this->directory)->files(); + + $this->assertCount(1, $finder); + + foreach ($finder as $file) { + $this->assertEquals($file->getFilename(), 'notsogrumpyanymore.jpeg'); + $this->assertEquals($file->getSize(), 1024); + } + } + public function tearDown() { $filesystem = new Filesystem(); diff --git a/Uploader/Storage/FlysystemStorage.php b/Uploader/Storage/FlysystemStorage.php index aa2fa61..08e6206 100644 --- a/Uploader/Storage/FlysystemStorage.php +++ b/Uploader/Storage/FlysystemStorage.php @@ -45,7 +45,7 @@ class FlysystemStorage implements StorageInterface } $stream = fopen($file->getPathname(), 'r+'); - $this->filesystem->putStream($name, $stream, array( + $this->filesystem->putStream($path, $stream, array( 'mimetype' => $file->getMimeType() )); if (is_resource($stream)) { diff --git a/composer.json b/composer.json index f3ebce1..ab88f2d 100644 --- a/composer.json +++ b/composer.json @@ -16,12 +16,12 @@ "require": { "php":">=5.4", - "symfony/framework-bundle": "^2.8|^3.0", - "symfony/finder": "^2.4.0|^3.0", - "symfony/translation": "^2.4.0|^3.0", - "symfony/asset": "^2.4.0|^3.0", - "symfony/templating": "^2.4.0|^3.0", - "paragonie/random_compat": "^1.1" + "symfony/framework-bundle": "^2.4|^3.0", + "symfony/finder": "^2.4|^3.0", + "symfony/translation": "^2.4|^3.0", + "symfony/asset": "^2.4|^3.0", + "symfony/templating": "^2.4|^3.0", + "paragonie/random_compat": "^1.1|^2.0" }, "require-dev": { commit 7f0f7b112a36f27ab0cb18368698bf74b65f1967 (from 774c82dd0c23716688e8ee818d7407a91990d436) Merge: 5cb66be 774c82d Author: David Greminger <[email protected]> Date: Tue Sep 19 12:55:12 2017 +0200 Merge branch 'master' into feature/symfony3-support diff --git a/.travis.yml b/.travis.yml index f9876e0..cd37eb1 100644 --- a/.travis.yml +++ b/.travis.yml @@ -6,12 +6,13 @@ php: - 5.6 - 7.0 - 7.1 - - hhvm env: - - SYMFONY_VERSION=2.4.* - SYMFONY_VERSION=2.7.* - SYMFONY_VERSION=2.8.* + - SYMFONY_VERSION=3.2.* + - SYMFONY_VERSION=3.3.* + - SYMFONY_VERSION=dev-master cache: directories: @@ -19,9 +20,6 @@ cache: matrix: allow_failures: - - php: hhvm - - php: 7.0 - - php: 7.1 - env: SYMFONY_VERSION=dev-master include: diff --git a/composer.json b/composer.json index 497d403..ab88f2d 100644 --- a/composer.json +++ b/composer.json @@ -16,19 +16,22 @@ "require": { "php":">=5.4", - "symfony/framework-bundle": "^2.4.0|~3.0", - "symfony/finder": "^2.4.0|~3.0", + "symfony/framework-bundle": "^2.4|^3.0", + "symfony/finder": "^2.4|^3.0", + "symfony/translation": "^2.4|^3.0", + "symfony/asset": "^2.4|^3.0", + "symfony/templating": "^2.4|^3.0", "paragonie/random_compat": "^1.1|^2.0" }, "require-dev": { "amazonwebservices/aws-sdk-for-php": "1.5.*", "knplabs/gaufrette": "0.2.*@dev", - "symfony/class-loader": "2.*|~3.0", - "symfony/security-bundle": "2.*|~3.0", - "sensio/framework-extra-bundle": "2.*|~3.0", - "symfony/browser-kit": "2.*|~3.0", - "phpunit/phpunit": "~4.4", + "symfony/class-loader": "2.*|^3.0", + "symfony/security-bundle": "2.*|^3.0", + "sensio/framework-extra-bundle": "2.*|^3.0", + "symfony/browser-kit": "2.*|^3.0", + "phpunit/phpunit": "^4.4", "oneup/flysystem-bundle": "^1.2" },
0
68e1534803d4c9f0338e007224e0bfe390079c39
1up-lab/OneupUploaderBundle
Refactored dynamic controllers.
commit 68e1534803d4c9f0338e007224e0bfe390079c39 Author: Jim Schmid <[email protected]> Date: Tue Mar 12 16:03:35 2013 +0100 Refactored dynamic controllers. diff --git a/Controller/UploadControllerInterface.php b/Controller/UploadControllerInterface.php new file mode 100644 index 0000000..977375e --- /dev/null +++ b/Controller/UploadControllerInterface.php @@ -0,0 +1,8 @@ +<?php + +namespace Oneup\UploaderBundle\Controller; + +interface UploadControllerInterface +{ + public function upload(); +} \ No newline at end of file diff --git a/Controller/UploaderController.php b/Controller/UploaderController.php index 0209311..f5e0b84 100644 --- a/Controller/UploaderController.php +++ b/Controller/UploaderController.php @@ -2,25 +2,44 @@ namespace Oneup\UploaderBundle\Controller; -class UploaderController +use Oneup\UploaderBundle\Controller\UploadControllerInterface; + +class UploaderController implements UploadControllerInterface { - protected $mappings; - protected $container; + protected $namer; + protected $storage; - public function __construct($mappings, $container) + public function __construct($namer, $storage) { - $this->mappings = $mappings; - $this->container = $container; + $this->namer = $namer; + $this->storage = $storage; } - public function upload($mapping) + public function upload() { + /* $container = $this->container; $config = $this->mappings[$mapping]; + $request = $container->get('request'); + $files = $request->files; if(!$container->has($config['storage'])) throw new \InvalidArgumentException(sprintf('The storage service "%s" must be defined.')); + + if(!$container->has($config['namer'])) + throw new \InvalidArgumentException(sprintf('The namer service "%s" must be defined.')); $storage = $container->get($config['storage']); + $namer = $container->get($config['namer']); + + var_dump($request); + + die(); + foreach($files as $file) + { + var_dump($namer->name($file, $config)); + } + */ + die(); } } \ No newline at end of file diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index afbd956..f5ece9d 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -14,13 +14,6 @@ class Configuration implements ConfigurationInterface $rootNode ->children() - ->arrayNode('routing') - ->addDefaultsIfNotSet() - ->children() - ->scalarNode('name')->defaultValue('/_uploader')->end() - ->scalarNode('action')->defaultValue('oneup_uploader.controller:upload')->end() - ->end() - ->end() ->arrayNode('chunks') ->addDefaultsIfNotSet() ->children() diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index 01ca0b3..8f8011b 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -2,6 +2,7 @@ namespace Oneup\UploaderBundle\DependencyInjection; +use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; use Symfony\Component\HttpKernel\DependencyInjection\Extension; @@ -17,12 +18,6 @@ class OneupUploaderExtension extends Extension $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('uploader.xml'); - // handle routing configuration - foreach($config['routing'] as $key => $value) - { - $container->setParameter(sprintf('oneup_uploader.routing.%s', $key), $value); - } - // handling chunk configuration if(!array_key_exists('directory', $config['chunks'])) { @@ -42,9 +37,23 @@ class OneupUploaderExtension extends Extension // handle mappings foreach($config['mappings'] as $key => $mapping) { - $container->setParameter(sprintf('oneup_uploader.mapping.%s', $key), $value); + $this->registerServicesPerMap($container, $key, $mapping); } - - $container->setParameter('oneup_uploader.mappings', $config['mappings']); + } + + public function registerServicesPerMap(ContainerBuilder $container, $type, $mapping) + { + // create controllers based on mapping + $container + ->register(sprintf('oneup_uploader.controller.%s', $type), $container->getParameter('oneup_uploader.controller.class')) + + // add the correct namer as argument + ->addArgument(new Reference($mapping['namer'])) + + // add the correspoding storage service as argument + ->addArgument(new Reference($mapping['storage'])) + + ->addTag('oneup_uploader.routable', array('type' => $type)) + ; } } \ No newline at end of file diff --git a/OneupUploaderBundle.php b/OneupUploaderBundle.php index 22c1af9..f359549 100644 --- a/OneupUploaderBundle.php +++ b/OneupUploaderBundle.php @@ -3,7 +3,16 @@ namespace Oneup\UploaderBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; +use Symfony\Component\DependencyInjection\ContainerBuilder; + +use Oneup\UploaderBundle\DependencyInjection\Compiler\ControllerCompilerPass; class OneupUploaderBundle extends Bundle { + public function build(ContainerBuilder $container) + { + parent::build($container); + + $container->addCompilerPass(new ControllerCompilerPass); + } } \ No newline at end of file diff --git a/Resources/config/uploader.xml b/Resources/config/uploader.xml index 11344b6..3816e43 100644 --- a/Resources/config/uploader.xml +++ b/Resources/config/uploader.xml @@ -23,18 +23,8 @@ <!-- namer --> <service id="oneup_uploader.namer.uniqid" class="%oneup_uploader.namer.uniqid.class%" /> - <!-- controller --> - <service id="oneup_uploader.controller" class="%oneup_uploader.controller.class%"> - <argument>%oneup_uploader.mappings%</argument> - <argument type="service" id="service_container" /> - </service> - <!-- routing --> <service id="oneup_uploader.routing.loader" class="%oneup_uploader.routing.loader.class%"> - <argument>%oneup_uploader.routing.action%</argument> - <argument>%oneup_uploader.routing.name%</argument> - <argument>%oneup_uploader.mappings%</argument> - <tag name="routing.loader" /> </service> diff --git a/Routing/RouteLoader.php b/Routing/RouteLoader.php index 881e0d9..771fb01 100644 --- a/Routing/RouteLoader.php +++ b/Routing/RouteLoader.php @@ -8,15 +8,17 @@ use Symfony\Component\Routing\RouteCollection; class RouteLoader extends Loader { - protected $action; - protected $prefix; - protected $mappings; + protected $name; + protected $controllers; - public function __construct($action, $name, array $mappings) + public function __construct() { - $this->name = $name; - $this->action = $action; - $this->mappings = $mappings; + $this->controllers = array(); + } + + public function addController($type, $controller) + { + $this->controllers[$type] = $controller; } public function supports($resource, $type = null) @@ -26,22 +28,17 @@ class RouteLoader extends Loader public function load($resource, $type = null) { - $requirements = array('_method' => 'POST', 'mapping' => '[A-z0-9_\-]*'); $routes = new RouteCollection(); - foreach($this->mappings as $key => $mapping) + foreach($this->controllers as $type => $service) { - $defaults = array( - '_controller' => is_null($mapping['action']) ? $this->action : $mapping['action'], - 'mapping' => $key + $route = new Route( + sprintf('/_uploader/%s', $type), + array('_controller' => $service . ':upload'), + array('_method' => 'POST') ); - $routes->add(sprintf('_uploader_%s', $key), new Route( - sprintf('%s/{mapping}', $this->name), - $defaults, - $requirements, - array() - )); + $routes->add(sprintf('_uploader_%s', $type), $route); } return $routes;
0
6441eb3bc730a7c678bbcb03f2eb13c5df44be9f
1up-lab/OneupUploaderBundle
Merge branch 'patch-1' of https://github.com/Th3Mouk/OneupUploaderBundle into Th3Mouk-patch-1
commit 6441eb3bc730a7c678bbcb03f2eb13c5df44be9f (from b330a5dc11d307f8820a7b740b8460f5346d9187) Merge: b330a5d 52205e6 Author: David Greminger <[email protected]> Date: Thu Dec 10 10:50:31 2015 +0100 Merge branch 'patch-1' of https://github.com/Th3Mouk/OneupUploaderBundle into Th3Mouk-patch-1 diff --git a/.travis.yml b/.travis.yml index 5a3affa..0af42e4 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,22 +5,29 @@ php: - 5.4 - 5.5 - 5.6 + - 7.0 - hhvm env: - - SYMFONY_VERSION=2.3.* + - SYMFONY_VERSION=2.7.* matrix: + include: + - php: 5.6 + env: SYMFONY_VERSION=2.3.* + - php: 5.6 + env: SYMFONY_VERSION=2.6.* + - php: 5.6 + env: SYMFONY_VERSION=2.7.* + - php: 5.6 + env: SYMFONY_VERSION=2.8.*@dev + - php: 5.6 + env: SYMFONY_VERSION="3.0.x-dev as 2.8" allow_failures: - - env: SYMFONY_VERSION=dev-master + - php: 7.0 - php: hhvm - include: - - php: 5.5 - env: SYMFONY_VERSION=2.4.* - - php: 5.5 - env: SYMFONY_VERSION=2.5.* - - php: 5.5 - env: SYMFONY_VERSION=dev-master + - env: SYMFONY_VERSION=2.8.*@dev + - env: SYMFONY_VERSION="3.0.x-dev as 2.8" before_script: - composer selfupdate commit 6441eb3bc730a7c678bbcb03f2eb13c5df44be9f (from 52205e6275347a3f1bfe3f607687a2921cef4487) Merge: b330a5d 52205e6 Author: David Greminger <[email protected]> Date: Thu Dec 10 10:50:31 2015 +0100 Merge branch 'patch-1' of https://github.com/Th3Mouk/OneupUploaderBundle into Th3Mouk-patch-1 diff --git a/Controller/AbstractController.php b/Controller/AbstractController.php index a551ba8..b150214 100644 --- a/Controller/AbstractController.php +++ b/Controller/AbstractController.php @@ -183,13 +183,14 @@ abstract class AbstractController * then the content type of the response will be set to text/plain instead. * * @param mixed $data + * @param int $statusCode * * @return JsonResponse */ - protected function createSupportedJsonResponse($data) + protected function createSupportedJsonResponse($data, $statusCode = 200) { $request = $this->container->get('request'); - $response = new JsonResponse($data); + $response = new JsonResponse($data, $statusCode); $response->headers->set('Vary', 'Accept'); if (!in_array('application/json', $request->getAcceptableContentTypes())) { diff --git a/Controller/DropzoneController.php b/Controller/DropzoneController.php index 2121f32..fd11420 100644 --- a/Controller/DropzoneController.php +++ b/Controller/DropzoneController.php @@ -14,11 +14,12 @@ class DropzoneController extends AbstractController $request = $this->container->get('request'); $response = new EmptyResponse(); $files = $this->getFiles($request->files); - + $statusCode = 200; foreach ($files as $file) { try { $this->handleUpload($file, $response, $request); } catch (UploadException $e) { + $statusCode = 500; //Dropzone displays error if HTTP response is 40x or 50x $this->errorHandler->addException($response, $e); $translator = $this->container->get('translator'); $message = $translator->trans($e->getMessage(), array(), 'OneupUploaderBundle'); @@ -28,6 +29,6 @@ class DropzoneController extends AbstractController } } - return $this->createSupportedJsonResponse($response->assemble()); + return $this->createSupportedJsonResponse($response->assemble(), $statusCode); } } diff --git a/Resources/config/errorhandler.xml b/Resources/config/errorhandler.xml index e684668..bf580bf 100644 --- a/Resources/config/errorhandler.xml +++ b/Resources/config/errorhandler.xml @@ -6,6 +6,7 @@ <parameters> <parameter key="oneup_uploader.error_handler.noop.class">Oneup\UploaderBundle\Uploader\ErrorHandler\NoopErrorHandler</parameter> <parameter key="oneup_uploader.error_handler.blueimp.class">Oneup\UploaderBundle\Uploader\ErrorHandler\BlueimpErrorHandler</parameter> + <parameter key="oneup_uploader.error_handler.dropzone.class">Oneup\UploaderBundle\Uploader\ErrorHandler\DropzoneErrorHandler</parameter> </parameters> <services> @@ -17,7 +18,7 @@ <service id="oneup_uploader.error_handler.fancyupload" class="%oneup_uploader.error_handler.noop.class%" public="false" /> <service id="oneup_uploader.error_handler.mooupload" class="%oneup_uploader.error_handler.noop.class%" public="false" /> <service id="oneup_uploader.error_handler.plupload" class="%oneup_uploader.error_handler.noop.class%" public="false" /> - <service id="oneup_uploader.error_handler.dropzone" class="%oneup_uploader.error_handler.noop.class%" public="false" /> + <service id="oneup_uploader.error_handler.dropzone" class="%oneup_uploader.error_handler.dropzone.class%" public="false" /> <service id="oneup_uploader.error_handler.custom" class="%oneup_uploader.error_handler.noop.class%" public="false" /> </services> diff --git a/Resources/doc/frontend_plupload.md b/Resources/doc/frontend_plupload.md index deb1ce0..0c2e01d 100644 --- a/Resources/doc/frontend_plupload.md +++ b/Resources/doc/frontend_plupload.md @@ -1,7 +1,7 @@ Use Plupload in your Symfony2 application ========================================= -Download [Plupload](http://http://www.plupload.com/) and include it in your template. Connect the `url` property to the dynamic route `_uploader_{mapping_name}`. +Download [Plupload](http://www.plupload.com/) and include it in your template. Connect the `url` property to the dynamic route `_uploader_{mapping_name}`. ```html <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> diff --git a/Twig/Extension/UploaderExtension.php b/Twig/Extension/UploaderExtension.php index c042e56..3cac14d 100644 --- a/Twig/Extension/UploaderExtension.php +++ b/Twig/Extension/UploaderExtension.php @@ -21,11 +21,11 @@ class UploaderExtension extends \Twig_Extension public function getFunctions() { return array( - 'oneup_uploader_endpoint' => new \Twig_Function_Method($this, 'endpoint'), - 'oneup_uploader_progress' => new \Twig_Function_Method($this, 'progress'), - 'oneup_uploader_cancel' => new \Twig_Function_Method($this, 'cancel'), - 'oneup_uploader_upload_key' => new \Twig_Function_Method($this, 'uploadKey'), - 'oneup_uploader_maxsize' => new \Twig_Function_Method($this, 'maxSize'), + new \Twig_SimpleFunction('oneup_uploader_endpoint', array($this, 'endpoint')), + new \Twig_SimpleFunction('oneup_uploader_progress', array($this, 'progress')), + new \Twig_SimpleFunction('oneup_uploader_cancel', array($this, 'cancel')), + new \Twig_SimpleFunction('oneup_uploader_upload_key', array($this, 'uploadKey')), + new \Twig_SimpleFunction('oneup_uploader_maxsize', array($this, 'maxSize')), ); } diff --git a/Uploader/Chunk/Storage/FilesystemStorage.php b/Uploader/Chunk/Storage/FilesystemStorage.php index 8855188..acc98d7 100644 --- a/Uploader/Chunk/Storage/FilesystemStorage.php +++ b/Uploader/Chunk/Storage/FilesystemStorage.php @@ -56,7 +56,7 @@ class FilesystemStorage implements ChunkStorageInterface throw new \InvalidArgumentException('The first argument must implement \IteratorAggregate interface.'); } - $iterator = $chunks->getIterator()->getInnerIterator(); + $iterator = $chunks->getIterator(); $base = $iterator->current(); $iterator->next(); diff --git a/Uploader/ErrorHandler/DropzoneErrorHandler.php b/Uploader/ErrorHandler/DropzoneErrorHandler.php new file mode 100755 index 0000000..5b0ad44 --- /dev/null +++ b/Uploader/ErrorHandler/DropzoneErrorHandler.php @@ -0,0 +1,19 @@ +<?php + +namespace Oneup\UploaderBundle\Uploader\ErrorHandler; + +use Exception; +use Oneup\UploaderBundle\Uploader\ErrorHandler\ErrorHandlerInterface; +use Oneup\UploaderBundle\Uploader\Response\AbstractResponse; + +class DropzoneErrorHandler implements ErrorHandlerInterface +{ + public function addException(AbstractResponse $response, Exception $exception) + { + $errors[] = $exception; + $message = $exception->getMessage(); + // Dropzone wants JSON with error message put into 'error' field. + // This overwrites the previous error message, so we're only displaying the last one. + $response['error'] = $message; + } +}
0
2a9913169e17de226a41ecc5ef3ed3cc7f4a04e1
1up-lab/OneupUploaderBundle
Return the name of the created file to FineUploader. Fixes #4
commit 2a9913169e17de226a41ecc5ef3ed3cc7f4a04e1 Author: Jim Schmid <[email protected]> Date: Thu Mar 14 21:32:57 2013 +0100 Return the name of the created file to FineUploader. Fixes #4 diff --git a/Controller/UploaderController.php b/Controller/UploaderController.php index 0d103a5..48aef6e 100644 --- a/Controller/UploaderController.php +++ b/Controller/UploaderController.php @@ -49,7 +49,7 @@ class UploaderController implements UploadControllerInterface { try { - $status = $totalParts > 1 ? $this->handleChunkedUpload($file) : $this->handleUpload($file); + $name = $totalParts > 1 ? $this->handleChunkedUpload($file) : $this->handleUpload($file); } catch(UploadException $e) { @@ -58,10 +58,7 @@ class UploaderController implements UploadControllerInterface } } - return $status ? - new JsonResponse(array('success' => true)): - new JsonResponse(array('error' => 'An unknown error occured.')) - ; + return new JsonResponse(array('success' => true, 'name' => $name)); } public function delete($uuid = null) @@ -118,7 +115,7 @@ class UploaderController implements UploadControllerInterface $this->dispatcher->dispatch(UploadEvents::POST_PERSIST, $postPersistEvent); } - return true; + return $name; } protected function handleChunkedUpload(UploadedFile $file) @@ -150,6 +147,6 @@ class UploaderController implements UploadControllerInterface $this->chunkManager->cleanup($path); } - return true; + return $name; } } \ No newline at end of file
0
584508cd9e45346c95e81f2e3ff74439d9c1f397
1up-lab/OneupUploaderBundle
Just dispatch PostDeleteEvent if the result from the Deleter was positive.
commit 584508cd9e45346c95e81f2e3ff74439d9c1f397 Author: Jim Schmid <[email protected]> Date: Thu Mar 14 20:09:29 2013 +0100 Just dispatch PostDeleteEvent if the result from the Deleter was positive. diff --git a/Controller/UploaderController.php b/Controller/UploaderController.php index affdd97..ddd87ea 100644 --- a/Controller/UploaderController.php +++ b/Controller/UploaderController.php @@ -70,12 +70,15 @@ class UploaderController implements UploadControllerInterface $result = $this->storage->remove($this->type, $uuid); - $postUploadEvent = new PostUploadEvent($this->request, $uuid, $this->type); - $this->dispatcher->dispatch(UploadEvents::POST_UPLOAD, $postUploadEvent); + if($result) + { + $postUploadEvent = new PostUploadEvent($this->request, $uuid, $this->type); + $this->dispatcher->dispatch(UploadEvents::POST_UPLOAD, $postUploadEvent); + + return new JsonResponse(array('success' => true)): + } - return $result ? - new JsonResponse(array('success' => true)): - new JsonResponse(array('error' => 'An unknown error occured.')); + return new JsonResponse(array('error' => 'An unknown error occured.')); } protected function handleUpload(UploadedFile $file)
0
64f970e45a8677a376b9e38ce63e1402469320d6
1up-lab/OneupUploaderBundle
Semantical typo fix (#315)
commit 64f970e45a8677a376b9e38ce63e1402469320d6 Author: Łukasz Chruściel <[email protected]> Date: Wed Jan 31 07:08:41 2018 +0100 Semantical typo fix (#315) diff --git a/Controller/AbstractController.php b/Controller/AbstractController.php index 55d57a0..1a12021 100644 --- a/Controller/AbstractController.php +++ b/Controller/AbstractController.php @@ -139,9 +139,9 @@ abstract class AbstractController $dispatcher = $this->container->get('event_dispatcher'); // dispatch pre upload event (both the specific and the general) - $postUploadEvent = new PreUploadEvent($uploaded, $response, $request, $this->type, $this->config); - $dispatcher->dispatch(UploadEvents::PRE_UPLOAD, $postUploadEvent); - $dispatcher->dispatch(sprintf('%s.%s', UploadEvents::PRE_UPLOAD, $this->type), $postUploadEvent); + $preUploadEvent = new PreUploadEvent($uploaded, $response, $request, $this->type, $this->config); + $dispatcher->dispatch(UploadEvents::PRE_UPLOAD, $preUploadEvent); + $dispatcher->dispatch(sprintf('%s.%s', UploadEvents::PRE_UPLOAD, $this->type), $preUploadEvent); } /**
0
1920b46c3c64e11c7bdae0471e4a774123a2e7bf
1up-lab/OneupUploaderBundle
Add utility methods to `PostUploadEvents` to generate mapping-specific event names (#350)
commit 1920b46c3c64e11c7bdae0471e4a774123a2e7bf Author: Mark Gerarts <[email protected]> Date: Sat Nov 17 22:55:27 2018 +0100 Add utility methods to `PostUploadEvents` to generate mapping-specific event names (#350) diff --git a/Resources/doc/events.md b/Resources/doc/events.md index 5fb6c4e..8f19824 100644 --- a/Resources/doc/events.md +++ b/Resources/doc/events.md @@ -17,8 +17,17 @@ Moreover this bundles also dispatches some special kind of generic events you ca * `oneup_uploader.post_upload.{mapping}` * `oneup_uploader.post_persist.{mapping}` * `oneup_uploader.post_chunk_upload.{mapping}` +* `oneup_uploader.validation.{mapping}` The `{mapping}` part is the key of your configured mapping. The examples in this documentation always uses the mapping key `gallery`. So the dispatched event would be called `oneup_uploader.post_upload.gallery`. -Using these generic events can save you some time and coding lines, as you don't have to check for the correct type in the `EventListener`. +Using these generic events can save you some time and coding lines, as you don't have to check for the correct type in the `EventListener`. The `UploadEvents` class provides some utility methods to generate these +mapping-specific event names. For example: -See the [custom logic section](custom_logic.md) of this documentation for specific examples on how to use these Events. \ No newline at end of file +```php +public static function getSubscribedEvents() +{ + return [UploadEvents::postUpload('gallery') => ['onPostUpload']]; +} +``` + +See the [custom logic section](custom_logic.md) of this documentation for specific examples on how to use these Events. diff --git a/Tests/UploadEventsTest.php b/Tests/UploadEventsTest.php new file mode 100644 index 0000000..2aba512 --- /dev/null +++ b/Tests/UploadEventsTest.php @@ -0,0 +1,44 @@ +<?php + +namespace Oneup\UploaderBundle\Tests; + +use Oneup\UploaderBundle\UploadEvents; +use PHPUnit\Framework\TestCase; + +class UploadEventsTest extends TestCase +{ + public function testPreUploadCanBePassedAMapping() + { + $event = UploadEvents::preUpload('gallery'); + + $this->assertEquals(UploadEvents::PRE_UPLOAD . '.gallery', $event); + } + + public function testPostUploadCanBePassedAMapping() + { + $event = UploadEvents::postUpload('gallery'); + + $this->assertEquals(UploadEvents::POST_UPLOAD . '.gallery', $event); + } + + public function testPostPersistCanBePassedAMapping() + { + $event = UploadEvents::postPersist('gallery'); + + $this->assertEquals(UploadEvents::POST_PERSIST . '.gallery', $event); + } + + public function testPostChunkUploadCanBePassedAMapping() + { + $event = UploadEvents::postChunkUpload('gallery'); + + $this->assertEquals(UploadEvents::POST_CHUNK_UPLOAD . '.gallery', $event); + } + + public function testValidationCanBePassedAMapping() + { + $event = UploadEvents::validation('gallery'); + + $this->assertEquals(UploadEvents::VALIDATION . '.gallery', $event); + } +} diff --git a/UploadEvents.php b/UploadEvents.php index 109000d..c4899cf 100644 --- a/UploadEvents.php +++ b/UploadEvents.php @@ -9,4 +9,34 @@ final class UploadEvents const POST_PERSIST = 'oneup_uploader.post_persist'; const POST_CHUNK_UPLOAD = 'oneup_uploader.post_chunk_upload'; const VALIDATION = 'oneup_uploader.validation'; + + public static function preUpload(string $mapping): string + { + return self::withMapping(self::PRE_UPLOAD, $mapping); + } + + public static function postUpload(string $mapping): string + { + return self::withMapping(self::POST_UPLOAD, $mapping); + } + + public static function postPersist(string $mapping): string + { + return self::withMapping(self::POST_PERSIST, $mapping); + } + + public static function postChunkUpload(string $mapping): string + { + return self::withMapping(self::POST_CHUNK_UPLOAD, $mapping); + } + + public static function validation(string $mapping): string + { + return self::withMapping(self::VALIDATION, $mapping); + } + + private static function withMapping(string $event, string $mapping): string + { + return "{$event}.{$mapping}"; + } }
0
c2920f67629a5f70ee5dd988648d6dec31b04db5
1up-lab/OneupUploaderBundle
Updated README.md adding a list of supported frontend libraries.
commit c2920f67629a5f70ee5dd988648d6dec31b04db5 Author: Jim Schmid <[email protected]> Date: Thu Apr 11 21:03:37 2013 +0200 Updated README.md adding a list of supported frontend libraries. diff --git a/README.md b/README.md index 857764b..f22a936 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,11 @@ OneupUploaderBundle =================== -The OneupUploaderBundle adds support for handling file uploads using the popular -Javascript library [Fine Uploader](http://fineuploader.com/). +The OneupUploaderBundle adds support for handling file uploads using one of the following Javascript libraries: + +* [FineUploader](http://fineuploader.com/) +* [jQuery File Uploader](http://blueimp.github.io/jQuery-File-Upload/) +* [YUI3 Uploader](http://yuilibrary.com/yui/docs/uploader/) +* [Uploadify](http://www.uploadify.com/) Features included:
0
5f473e57c65535f2c85aba550c30af1717f7922f
1up-lab/OneupUploaderBundle
Added doc blocks to ReponseInterface
commit 5f473e57c65535f2c85aba550c30af1717f7922f Author: Jim Schmid <[email protected]> Date: Tue Aug 13 16:01:43 2013 +0200 Added doc blocks to ReponseInterface diff --git a/Uploader/Response/ResponseInterface.php b/Uploader/Response/ResponseInterface.php index 135ef3a..517b796 100644 --- a/Uploader/Response/ResponseInterface.php +++ b/Uploader/Response/ResponseInterface.php @@ -4,5 +4,10 @@ namespace Oneup\UploaderBundle\Uploader\Response; interface ResponseInterface { + /** + * Transforms this object to an array of data + * + * @return array + */ public function assemble(); }
0
4351643af4dce59605f57a3937f3afbf40da2670
1up-lab/OneupUploaderBundle
Added syntax hightlight indicator.
commit 4351643af4dce59605f57a3937f3afbf40da2670 Author: Jim Schmid <[email protected]> Date: Sun Apr 7 13:09:52 2013 +0200 Added syntax hightlight indicator. diff --git a/Resources/doc/index.md b/Resources/doc/index.md index 05a27f0..47145c2 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -9,7 +9,7 @@ This bundle tested using Symfony2 versions 2.1+. If you wish to use the default texts provided with this bundle, you have to make sure that you have translator enabled in your configuration file. -``` +```yaml # app/config/config.yml framework: @@ -64,7 +64,7 @@ public function registerBundles() This bundle was designed to just work out of the box. The only thing you have to configure in order to get this bundle up and running is a mapping. -``` +```yaml # app/config/config.yml oneup_uploader: @@ -77,7 +77,7 @@ As this is a server implementation for Fine Uploader, you have to include this l _uploader_{mapping_key} -``` +```html <script type="text/javascript" src="js/jquery-1.9.1.min.js"></script> <script type="text/javascript" src="js/jquery.fineuploader-3.4.1.js"></script> <script type="text/javascript">
0
6db9e56ab3996511a8cf9e1dda844fa89a92e525
1up-lab/OneupUploaderBundle
Merge pull request #16 from 1up-lab/improved-tests Improved tests
commit 6db9e56ab3996511a8cf9e1dda844fa89a92e525 (from c57af49653c22110a065c01296bfdb283c9f045d) Merge: c57af49 2227d8b Author: Jim Schmid <[email protected]> Date: Mon May 6 13:34:59 2013 -0700 Merge pull request #16 from 1up-lab/improved-tests Improved tests diff --git a/.gitignore b/.gitignore index 820d851..7c766c7 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,5 @@ composer.lock phpunit.xml vendor log +Tests/App/cache +Tests/App/logs \ No newline at end of file diff --git a/.travis.yml b/.travis.yml index d231b7e..40d1a2d 100644 --- a/.travis.yml +++ b/.travis.yml @@ -7,7 +7,6 @@ php: env: - SYMFONY_VERSION=2.1.* - SYMFONY_VERSION=2.2.* - - SYMFONY_VERSION=dev-master before_script: - composer require symfony/framework-bundle:${SYMFONY_VERSION} --prefer-source diff --git a/Tests/App/AppKernel.php b/Tests/App/AppKernel.php new file mode 100644 index 0000000..2e39ab8 --- /dev/null +++ b/Tests/App/AppKernel.php @@ -0,0 +1,28 @@ +<?php + +use Symfony\Component\HttpKernel\Kernel; +use Symfony\Component\Config\Loader\LoaderInterface; + +class AppKernel extends Kernel +{ + public function registerBundles() + { + $bundles = array( + new Symfony\Bundle\FrameworkBundle\FrameworkBundle(), + new Symfony\Bundle\SecurityBundle\SecurityBundle(), + new Symfony\Bundle\MonologBundle\MonologBundle(), + new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(), + new JMS\SerializerBundle\JMSSerializerBundle($this), + + // bundle to test + new Oneup\UploaderBundle\OneupUploaderBundle(), + ); + + return $bundles; + } + + public function registerContainerConfiguration(LoaderInterface $loader) + { + $loader->load(__DIR__.'/config/config.yml'); + } +} diff --git a/Tests/App/config/config.yml b/Tests/App/config/config.yml new file mode 100644 index 0000000..de85d76 --- /dev/null +++ b/Tests/App/config/config.yml @@ -0,0 +1,35 @@ +framework: + translator: { fallback: en } + secret: secret + router: + resource: "%kernel.root_dir%/config/routing.yml" + strict_requirements: %kernel.debug% + templating: + engines: ['php'] + default_locale: en + session: ~ + test: ~ + +monolog: + handlers: + main: + type: fingers_crossed + action_level: error + handler: nested + nested: + type: stream + path: %kernel.logs_dir%/%kernel.environment%.log + level: debug + +oneup_uploader: + mappings: + + fineuploader: + frontend: fineuploader + storage: + directory: %kernel.root_dir%/cache/%kernel.environment%/upload + + blueimp: + frontend: blueimp + storage: + directory: %kernel.root_dir%/cache/%kernel.environment%/upload \ No newline at end of file diff --git a/Tests/App/config/routing.yml b/Tests/App/config/routing.yml new file mode 100644 index 0000000..71cd825 --- /dev/null +++ b/Tests/App/config/routing.yml @@ -0,0 +1,3 @@ +oneup_uploader: + resource: . + type: uploader \ No newline at end of file diff --git a/Tests/Controller/AbstractControllerChunkedTest.php b/Tests/Controller/AbstractControllerChunkedTest.php deleted file mode 100644 index 771282f..0000000 --- a/Tests/Controller/AbstractControllerChunkedTest.php +++ /dev/null @@ -1,147 +0,0 @@ -<?php - -namespace Oneup\UploaderBundle\Tests\Controller; - -use Symfony\Component\Finder\Finder; -use Symfony\Component\Filesystem\Filesystem; -use Symfony\Component\HttpFoundation\File\UploadedFile; - -use Oneup\UploaderBundle\Uploader\Chunk\ChunkManager; -use Oneup\UploaderBundle\Uploader\Naming\UniqidNamer; -use Oneup\UploaderBundle\Uploader\Storage\FilesystemStorage; - -abstract class AbstractControllerChunkedTest extends \PHPUnit_Framework_TestCase -{ - protected $tempChunks; - protected $currentChunk; - protected $chunkUuid; - protected $numberOfChunks; - - abstract public function getControllerString(); - abstract protected function getRequestMock(); - - public function setUp() - { - $this->numberOfChunks = 10; - - // create 10 chunks - for($i = 0; $i < $this->numberOfChunks; $i++) - { - // create temporary file - $chunk = tempnam(sys_get_temp_dir(), 'uploader'); - - $pointer = fopen($chunk, 'w+'); - fwrite($pointer, str_repeat('A', 1024), 1024); - fclose($pointer); - - $this->tempChunks[] = $chunk; - } - - $this->currentChunk = 0; - $this->chunkUuid = uniqid(); - } - - public function testUpload() - { - $container = $this->getContainerMock(); - $storage = new FilesystemStorage(sys_get_temp_dir() . '/uploader'); - $config = array( - 'use_orphanage' => false, - 'namer' => 'namer', - 'max_size' => 2048, - 'allowed_extensions' => array(), - 'disallowed_extensions' => array() - ); - - $responses = array(); - $str = $this->getControllerString(); - $controller = new $str($container, $storage, $config, 'cat'); - - // mock as much requests as there are parts to assemble - for($i = 0; $i < $this->numberOfChunks; $i ++) - { - $responses[] = $controller->upload(); - - // will be used internaly - $this->currentChunk++; - } - - for($i = 0; $i < $this->numberOfChunks; $i ++) - { - // check if original file has been moved - $this->assertFalse(file_exists($this->tempChunks[$i])); - - $this->assertInstanceOf('Symfony\Component\HttpFoundation\JsonResponse', $responses[$i]); - $this->assertEquals(200, $responses[$i]->getStatusCode()); - } - - // check if assembled file is here - $finder = new Finder(); - $finder->in(sys_get_temp_dir() . '/uploader')->files(); - $this->assertCount(1, $finder); - - // and check if chunks are gone - $finder = new Finder(); - $finder->in(sys_get_temp_dir() . '/chunks')->files(); - $this->assertCount(0, $finder); - } - - protected function getContainerMock() - { - $mock = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface'); - $mock - ->expects($this->any()) - ->method('get') - ->will($this->returnCallback(array($this, 'containerGetCb'))) - ; - - return $mock; - } - - public function containerGetCb($inp) - { - if($inp == 'request') - return $this->getRequestMock(); - - if($inp == 'event_dispatcher') - return $this->getEventDispatcherMock(); - - if($inp == 'namer') - return new UniqidNamer(); - - if($inp == 'oneup_uploader.chunk_manager') - return $this->getChunkManager(); - } - - protected function getEventDispatcherMock() - { - $mock = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface'); - $mock - ->expects($this->any()) - ->method('dispatch') - ->will($this->returnValue(true)) - ; - - return $mock; - } - - protected function getUploadedFile() - { - return new UploadedFile($this->tempChunks[$this->currentChunk], 'grumpy-cat.jpeg', 'image/jpeg', 1024, null, true); - } - - protected function getChunkManager() - { - return new ChunkManager(array( - 'directory' => sys_get_temp_dir() . '/chunks' - )); - } - - public function tearDown() - { - // remove all files in tmp folder - $filesystem = new Filesystem(); - $filesystem->remove(sys_get_temp_dir() . '/uploader'); - $filesystem->remove(sys_get_temp_dir() . '/chunks'); - } -} \ No newline at end of file diff --git a/Tests/Controller/AbstractControllerTest.php b/Tests/Controller/AbstractControllerTest.php index 80176e9..14c966f 100644 --- a/Tests/Controller/AbstractControllerTest.php +++ b/Tests/Controller/AbstractControllerTest.php @@ -3,142 +3,127 @@ namespace Oneup\UploaderBundle\Tests\Controller; use Symfony\Component\Finder\Finder; -use Symfony\Component\Filesystem\Filesystem; -use Symfony\Component\HttpFoundation\File\UploadedFile; +use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; -use Oneup\UploaderBundle\Uploader\Naming\UniqidNamer; -use Oneup\UploaderBundle\Uploader\Storage\FilesystemStorage; - -abstract class AbstractControllerTest extends \PHPUnit_Framework_TestCase +abstract class AbstractControllerTest extends WebTestCase { - protected $tempFile; - - abstract public function getControllerString(); - abstract protected function getRequestMock(); + protected $client; + protected $container; + protected $createdFiles; public function setUp() { - // create temporary file - $this->tempFile = tempnam(sys_get_temp_dir(), 'uploader'); + $this->client = static::createClient(); + $this->container = $this->client->getContainer(); + $this->helper = $this->container->get('oneup_uploader.templating.uploader_helper'); + $this->createdFiles = array(); - $pointer = fopen($this->tempFile, 'w+'); - fwrite($pointer, str_repeat('A', 1024), 1024); - fclose($pointer); + $routes = $this->container->get('router')->getRouteCollection()->all(); } - public function testUpload() + abstract protected function getConfigKey(); + abstract protected function getRequestParameters(); + abstract protected function getRequestFile(); + + public function testSingleUpload() { - $container = $this->getContainerMock(); - $storage = new FilesystemStorage(sys_get_temp_dir() . '/uploader'); - $config = array( - 'use_orphanage' => false, - 'namer' => 'namer', - 'max_size' => 2048, - 'allowed_extensions' => array(), - 'disallowed_extensions' => array() - ); + // assemble a request + $client = $this->client; + $endpoint = $this->helper->endpoint($this->getConfigKey()); - $str = $this->getControllerString(); - $controller = new $str($container, $storage, $config, 'cat'); - $response = $controller->upload(); + $client->request('POST', $endpoint, $this->getRequestParameters(), array($this->getRequestFile())); + $response = $client->getResponse(); - // check if original file has been moved - $this->assertFalse(file_exists($this->tempFile)); - - // testing response - $this->assertInstanceOf('Symfony\Component\HttpFoundation\JsonResponse', $response); - $this->assertEquals(200, $response->getStatusCode()); - - // check if file is present - $finder = new Finder(); - $finder->in(sys_get_temp_dir() . '/uploader')->files(); + $this->assertTrue($response->isSuccessful()); + $this->assertEquals($response->headers->get('Content-Type'), 'application/json'); + $this->assertCount(1, $this->getUploadedFiles()); - $this->assertCount(1, $finder); + foreach($this->getUploadedFiles() as $file) { + $this->assertTrue($file->isFile()); + $this->assertTrue($file->isReadable()); + $this->assertEquals(128, $file->getSize()); + } } - public function testUploadWhichFails() + public function testRoute() { - $container = $this->getContainerMock(); - $storage = new FilesystemStorage(sys_get_temp_dir() . '/uploader'); - $config = array( - 'use_orphanage' => false, - 'namer' => 'namer', - 'max_size' => 1, - 'allowed_extensions' => array(), - 'disallowed_extensions' => array() - ); + $endpoint = $this->helper->endpoint($this->getConfigKey()); - $str = $this->getControllerString(); - $controller = new $str($container, $storage, $config, 'cat'); - $response = $controller->upload(); - - $json = json_decode($response->getContent()); - - // testing response - $this->assertInstanceOf('Symfony\Component\HttpFoundation\JsonResponse', $response); - $this->assertEquals(200, $response->getStatusCode()); + $this->assertNotNull($endpoint); + $this->assertEquals(0, strpos('_uploader', $endpoint)); } - protected function getContainerMock() + /** + * @expectedException Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException + */ + public function testCallByGet() { - $mock = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface'); - $mock - ->expects($this->any()) - ->method('get') - ->will($this->returnCallback(array($this, 'containerGetCb'))) - ; - - return $mock; + $endpoint = $this->helper->endpoint($this->getConfigKey()); + $this->client->request('GET', $endpoint); } - public function containerGetCb($inp) + /** + * @expectedException Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException + */ + public function testCallByDelete() { - if($inp == 'request') - return $this->getRequestMock(); - - if($inp == 'event_dispatcher') - return $this->getEventDispatcherMock(); - - if($inp == 'namer') - return new UniqidNamer(); - - if($inp == 'translator') - return $this->getTranslatorMock(); + $endpoint = $this->helper->endpoint($this->getConfigKey()); + $this->client->request('DELETE', $endpoint); + } + + /** + * @expectedException Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException + */ + public function testCallByPut() + { + $endpoint = $this->helper->endpoint($this->getConfigKey()); + $this->client->request('PUT', $endpoint); } - protected function getEventDispatcherMock() + public function testCallByPost() { - $mock = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface'); - $mock - ->expects($this->any()) - ->method('dispatch') - ->will($this->returnValue(true)) - ; + $client = $this->client; + $endpoint = $this->helper->endpoint($this->getConfigKey()); + + $client->request('POST', $endpoint); + $response = $client->getResponse(); - return $mock; + $this->assertTrue($response->isSuccessful()); + $this->assertEquals($response->headers->get('Content-Type'), 'application/json'); } - protected function getTranslatorMock() + protected function createTempFile($size = 128) { - $mock = $this->getMock('Symfony\Component\Translation\TranslatorInterface'); - $mock - ->expects($this->any()) - ->method('trans') - ->will($this->returnValue('A translated error.')) - ; + $file = tempnam(sys_get_temp_dir(), 'uploader_'); + file_put_contents($file, str_repeat('A', $size)); + + $this->createdFiles[] = $file; - return $mock; + return $file; } - protected function getUploadedFile() + protected function getUploadedFiles() { - return new UploadedFile($this->tempFile, 'grumpy-cat.jpeg', 'image/jpeg', 1024, null, true); + $env = $this->container->getParameter('kernel.environment'); + $root = $this->container->getParameter('kernel.root_dir'); + + // assemble path + $path = sprintf('%s/cache/%s/upload', $root, $env); + + $finder = new Finder(); + $files = $finder->in($path); + + return $files; } public function tearDown() { - // remove all files in tmp folder - $filesystem = new Filesystem(); - $filesystem->remove(sys_get_temp_dir() . '/uploader'); + foreach($this->createdFiles as $file) { + @unlink($file); + } + + foreach($this->getUploadedFiles() as $file) { + @unlink($file); + } } -} \ No newline at end of file +} diff --git a/Tests/Controller/BlueimpControllerChunkedTest.php b/Tests/Controller/BlueimpControllerChunkedTest.php deleted file mode 100644 index 9b95ca5..0000000 --- a/Tests/Controller/BlueimpControllerChunkedTest.php +++ /dev/null @@ -1,71 +0,0 @@ -<?php - -namespace Oneup\UploaderBundle\Tests\Controller; - -use Oneup\UploaderBundle\Tests\Controller\AbstractControllerChunkedTest; - -class BlueimpControllerChunkedTest extends AbstractControllerChunkedTest -{ - public function getControllerString() - { - return 'Oneup\UploaderBundle\Controller\BlueimpController'; - } - - protected function getRequestMock() - { - $mock = $this->getMock('Symfony\Component\HttpFoundation\Request'); - - $headers = $this->getMock('Symfony\Component\HttpFoundation\HeaderBag'); - $headers - ->expects($this->any()) - ->method('get') - ->will($this->returnCallback(array($this, 'headersGetCb'))) - ; - - $mock->headers = $headers; - - $mock->files = array( - array($this->getUploadedFile()) - ); - - return $mock; - } - - public function containerGetCb($inp) - { - if($inp == 'session') - { - $mock = $this->getMock('Symfony\Component\HttpFoundation\Session\Session'); - $mock - ->expects($this->any()) - ->method('getId') - ->will($this->returnValue('fixed-id')) - ; - - return $mock; - } - - return parent::containerGetCb($inp); - } - - public function headersGetCb($inp) - { - if($inp == 'content-disposition') - return 'grumpy-cat.jpeg'; - - if($inp == 'content-range') - { - if($this->currentChunk == ($this->numberOfChunks - 1)) - { - return sprintf('- 9218, 10240/10241'); - } - else - { - $size = 1024; - $ret = sprintf('- %d, %d/%d', $this->currentChunk * $size, $this->currentChunk * $size + $size, 10240); - - return $ret; - } - } - } -} diff --git a/Tests/Controller/BlueimpControllerTest.php b/Tests/Controller/BlueimpControllerTest.php deleted file mode 100644 index 19ffefa..0000000 --- a/Tests/Controller/BlueimpControllerTest.php +++ /dev/null @@ -1,32 +0,0 @@ -<?php - -namespace Oneup\UploaderBundle\Tests\Controller; - -use Oneup\UploaderBundle\Tests\Controller\AbstractControllerTest; - -class BlueimpControllerTest extends AbstractControllerTest -{ - public function getControllerString() - { - return 'Oneup\UploaderBundle\Controller\BlueimpController'; - } - - protected function getRequestMock() - { - $mock = $this->getMock('Symfony\Component\HttpFoundation\Request'); - $headers = $this->getMock('Symfony\Component\HttpFoundation\HeaderBag'); - $headers - ->expects($this->any()) - ->method('get') - ->will($this->returnValue(null)) - ; - - $mock->headers = $headers; - - $mock->files = array( - array($this->getUploadedFile()) - ); - - return $mock; - } -} \ No newline at end of file diff --git a/Tests/Controller/BlueimpTest.php b/Tests/Controller/BlueimpTest.php new file mode 100644 index 0000000..51c9918 --- /dev/null +++ b/Tests/Controller/BlueimpTest.php @@ -0,0 +1,29 @@ +<?php + +namespace Oneup\UploaderBundle\Tests\Controller; + +use Symfony\Component\HttpFoundation\File\UploadedFile; +use Oneup\UploaderBundle\Tests\Controller\AbstractControllerTest; + +class BlueimpTest extends AbstractControllerTest +{ + protected function getConfigKey() + { + return 'blueimp'; + } + + protected function getRequestParameters() + { + return array(); + } + + protected function getRequestFile() + { + return array(new UploadedFile( + $this->createTempFile(128), + 'cat.txt', + 'text/plain', + 128 + )); + } +} diff --git a/Tests/Controller/FineUploaderControllerChunkedTest.php b/Tests/Controller/FineUploaderControllerChunkedTest.php deleted file mode 100644 index 9d9adb1..0000000 --- a/Tests/Controller/FineUploaderControllerChunkedTest.php +++ /dev/null @@ -1,44 +0,0 @@ -<?php - -namespace Oneup\UploaderBundle\Tests\Controller; - -use Oneup\UploaderBundle\Tests\Controller\AbstractControllerChunkedTest; - -class FineUploaderControllerChunkedTest extends AbstractControllerChunkedTest -{ - public function getControllerString() - { - return 'Oneup\UploaderBundle\Controller\FineUploaderController'; - } - - protected function getRequestMock() - { - $mock = $this->getMock('Symfony\Component\HttpFoundation\Request'); - $mock - ->expects($this->any()) - ->method('get') - ->will($this->returnCallback(array($this, 'requestGetCb'))) - ; - - $mock->files = array( - $this->getUploadedFile() - ); - - return $mock; - } - - public function requestGetCb($inp) - { - if($inp == 'qqtotalparts') - return $this->numberOfChunks; - - if($inp == 'qqpartindex') - return $this->currentChunk; - - if($inp == 'qquuid') - return $this->chunkUuid; - - if($inp == 'qqfilename') - return 'grumpy-cat.jpeg'; - } -} \ No newline at end of file diff --git a/Tests/Controller/FineUploaderControllerTest.php b/Tests/Controller/FineUploaderControllerTest.php deleted file mode 100644 index 5fafc14..0000000 --- a/Tests/Controller/FineUploaderControllerTest.php +++ /dev/null @@ -1,30 +0,0 @@ -<?php - -namespace Oneup\UploaderBundle\Tests\Controller; - -use Oneup\UploaderBundle\Tests\Controller\AbstractControllerTest; - -class FineUploaderControllerTest extends AbstractControllerTest -{ - public function getControllerString() - { - return 'Oneup\UploaderBundle\Controller\FineUploaderController'; - } - - protected function getRequestMock() - { - $mock = $this->getMock('Symfony\Component\HttpFoundation\Request'); - $mock - ->expects($this->any()) - ->method('get') - ->with('qqtotalparts') - ->will($this->returnValue(1)) - ; - - $mock->files = array( - $this->getUploadedFile() - ); - - return $mock; - } -} \ No newline at end of file diff --git a/Tests/Controller/FineUploaderTest.php b/Tests/Controller/FineUploaderTest.php new file mode 100644 index 0000000..7c6ec11 --- /dev/null +++ b/Tests/Controller/FineUploaderTest.php @@ -0,0 +1,29 @@ +<?php + +namespace Oneup\UploaderBundle\Tests\Controller; + +use Symfony\Component\HttpFoundation\File\UploadedFile; +use Oneup\UploaderBundle\Tests\Controller\AbstractControllerTest; + +class FineUploaderTest extends AbstractControllerTest +{ + protected function getConfigKey() + { + return 'fineuploader'; + } + + protected function getRequestParameters() + { + return array(); + } + + protected function getRequestFile() + { + return new UploadedFile( + $this->createTempFile(128), + 'cat.txt', + 'text/plain', + 128 + ); + } +} diff --git a/Tests/bootstrap.php b/Tests/bootstrap.php index 1f4f67c..5b67409 100644 --- a/Tests/bootstrap.php +++ b/Tests/bootstrap.php @@ -1,8 +1,22 @@ <?php -$file = __DIR__.'/../vendor/autoload.php'; -if (!file_exists($file)) { - throw new RuntimeException('Install dependencies to run test suite.'); +$loader = @include __DIR__ . '/../vendor/autoload.php'; +if (!$loader) { + die(<<<'EOT' +You must set up the project dependencies, run the following commands: +wget http://getcomposer.org/composer.phar +php composer.phar install +EOT + ); } -$autoload = require_once $file; \ No newline at end of file +spl_autoload_register(function($class) { + if (0 === strpos($class, 'Oneup\\UploaderBundle\\')) { + $path = __DIR__.'/../'.implode('/', array_slice(explode('\\', $class), 2)).'.php'; + if (!stream_resolve_include_path($path)) { + return false; + } + require_once $path; + return true; + } +}); diff --git a/composer.json b/composer.json index b312ae5..5a86478 100644 --- a/composer.json +++ b/composer.json @@ -18,7 +18,16 @@ }, "require-dev": { - "knplabs/gaufrette": "0.2.*@dev" + "knplabs/gaufrette": "0.2.*@dev", + "symfony/class-loader": "2.*", + "symfony/security-bundle": "2.*", + "symfony/monolog-bundle": "2.*", + "sensio/framework-extra-bundle": "2.*", + "jms/serializer-bundle": "dev-master", + "symfony/yaml": "2.*", + "symfony/form": "2.*", + "symfony/twig-bundle": "2.*", + "symfony/browser-kit": "2.*" }, "suggest": { diff --git a/phpunit.xml.dist b/phpunit.xml.dist index f3c7e3e..07c869d 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -1,7 +1,10 @@ <?xml version="1.0" encoding="UTF-8"?> <phpunit bootstrap="./Tests/bootstrap.php" colors="true"> - + <php> + <server name="KERNEL_DIR" value="Tests/App" /> + </php> + <testsuites> <testsuite name="OneupUploaderBundle test suite"> <directory suffix="Test.php">./Tests</directory>
0
5d61e56cdf0132ea1d39e6304f9a4f45d84372cf
1up-lab/OneupUploaderBundle
Improve example on custom logic
commit 5d61e56cdf0132ea1d39e6304f9a4f45d84372cf Author: JHGitty <[email protected]> Date: Sat Jan 30 03:17:59 2016 +0100 Improve example on custom logic diff --git a/Resources/doc/custom_logic.md b/Resources/doc/custom_logic.md index ccb915e..6fea373 100644 --- a/Resources/doc/custom_logic.md +++ b/Resources/doc/custom_logic.md @@ -11,15 +11,21 @@ In almost every use case you need to further process uploaded files. For example To listen to one of these events you need to create an `EventListener`. ```php -namespace Acme\HelloBundle\EventListener; +namespace AppBundle\EventListener; +use Doctrine\Common\Persistence\ObjectManager; use Oneup\UploaderBundle\Event\PostPersistEvent; class UploadListener { - public function __construct($doctrine) + /** + * @var ObjectManager + */ + private $om; + + public function __construct(ObjectManager $om) { - $this->doctrine = $doctrine; + $this->om = $om; } public function onUpload(PostPersistEvent $event) @@ -33,7 +39,7 @@ And register it in your `services.xml`. ```xml <services> - <service id="acme_hello.upload_listener" class="Acme\HelloBundle\EventListener\UploadListener"> + <service id="app.upload_listener" class="AppBundle\EventListener\UploadListener"> <argument type="service" id="doctrine" /> <tag name="kernel.event_listener" event="oneup_uploader.post_persist" method="onUpload" /> </service> @@ -43,8 +49,8 @@ And register it in your `services.xml`. ```yml services: acme_hello.upload_listener: - class: Acme\HelloBundle\EventListener\UploadListener - argument: ["@doctrine"] + class: AppBundle\EventListener\UploadListener + argument: ["@doctrine.orm.entity_manager"] tags: - { name: kernel.event_listener, event: oneup_uploader.post_persist, method: onUpload } ``` @@ -114,6 +120,6 @@ use Symfony\Component\HttpFoundation\File\Exception\UploadException; public function onUpload(PostPersistEvent $event) { // Remember to remove the already uploaded file - throw new UploadException('Nope, I dont do files'); + throw new UploadException('Nope, I don\'t do files.'); } ```
0
42e611f3c377f99f1cf32d859e26dad4cf2c3ab1
1up-lab/OneupUploaderBundle
Remove unneeded check in constructor
commit 42e611f3c377f99f1cf32d859e26dad4cf2c3ab1 Author: Jérôme Parmentier <[email protected]> Date: Fri Oct 6 17:59:07 2017 +0200 Remove unneeded check in constructor diff --git a/Uploader/Chunk/Storage/FlysystemStorage.php b/Uploader/Chunk/Storage/FlysystemStorage.php index 5afbfa5..77eabc6 100644 --- a/Uploader/Chunk/Storage/FlysystemStorage.php +++ b/Uploader/Chunk/Storage/FlysystemStorage.php @@ -22,14 +22,6 @@ class FlysystemStorage implements ChunkStorageInterface public function __construct(Filesystem $filesystem, $bufferSize, $streamWrapperPrefix, $prefix) { - if ( - !method_exists($filesystem, 'readStream') - || - !method_exists($filesystem, 'putStream') - ) { - throw new \InvalidArgumentException('The filesystem used as chunk storage must streamable'); - } - if (null === $streamWrapperPrefix) { throw new \InvalidArgumentException('Stream wrapper must be configured.'); }
0
e6550e82a7c64a9c952f03364fafb5c27049d88d
1up-lab/OneupUploaderBundle
Messed up the links. Sorry.
commit e6550e82a7c64a9c952f03364fafb5c27049d88d Author: Jim Schmid <[email protected]> Date: Thu Apr 18 19:04:12 2013 +0200 Messed up the links. Sorry. diff --git a/Resources/doc/events.md b/Resources/doc/events.md index 30244f2..4edba13 100644 --- a/Resources/doc/events.md +++ b/Resources/doc/events.md @@ -14,4 +14,4 @@ Moreover this bundles also dispatches some special kind of generic events you ca The `{mapping}` part is the key of your configured mapping. The examples in this documentation always uses the mapping key `gallery`. So the dispatched event would be called `oneup_uploader.post_upload.gallery`. Using these generic events can save you some time and coding lines, as you don't have to check for the correct type in the `EventListener`. -See the [custom_logic.md](custom logic section) of this documentation for specific examples on how to use these Events. \ No newline at end of file +See the [custom logic section](custom_logic.md) of this documentation for specific examples on how to use these Events. \ No newline at end of file
0
4c5be73f6b16810f7296382320c87d982df2d85c
1up-lab/OneupUploaderBundle
Tested max_size contraint.
commit 4c5be73f6b16810f7296382320c87d982df2d85c Author: Jim Schmid <[email protected]> Date: Sat Jun 22 16:51:10 2013 +0200 Tested max_size contraint. diff --git a/Tests/App/config/config.yml b/Tests/App/config/config.yml index 96b50d3..77da381 100644 --- a/Tests/App/config/config.yml +++ b/Tests/App/config/config.yml @@ -31,6 +31,7 @@ oneup_uploader: fineuploader_validation: frontend: fineuploader + max_size: 256 storage: directory: %kernel.root_dir%/cache/%kernel.environment%/upload allowed_extensions: [ "ok" ] @@ -45,6 +46,7 @@ oneup_uploader: fancyupload_validation: frontend: fancyupload + max_size: 256 storage: directory: %kernel.root_dir%/cache/%kernel.environment%/upload allowed_extensions: [ "ok" ] @@ -59,6 +61,7 @@ oneup_uploader: yui3_validation: frontend: yui3 + max_size: 256 storage: directory: %kernel.root_dir%/cache/%kernel.environment%/upload allowed_extensions: [ "ok" ] @@ -73,6 +76,7 @@ oneup_uploader: plupload_validation: frontend: plupload + max_size: 256 storage: directory: %kernel.root_dir%/cache/%kernel.environment%/upload allowed_extensions: [ "ok" ] @@ -87,6 +91,7 @@ oneup_uploader: uploadify_validation: frontend: uploadify + max_size: 256 storage: directory: %kernel.root_dir%/cache/%kernel.environment%/upload allowed_extensions: [ "ok" ] @@ -101,6 +106,7 @@ oneup_uploader: blueimp_validation: frontend: blueimp + max_size: 256 storage: directory: %kernel.root_dir%/cache/%kernel.environment%/upload allowed_extensions: [ "ok" ] diff --git a/Tests/Controller/AbstractUploadTest.php b/Tests/Controller/AbstractUploadTest.php index 6dfc7e4..e84dd20 100644 --- a/Tests/Controller/AbstractUploadTest.php +++ b/Tests/Controller/AbstractUploadTest.php @@ -49,13 +49,13 @@ abstract class AbstractUploadTest extends AbstractControllerTest $me = $this; $uploadCount = 0; $preValidation = 1; - + $dispatcher->addListener(UploadEvents::PRE_UPLOAD, function(PreUploadEvent $event) use (&$uploadCount, &$me, &$preValidation) { $preValidation -= 2; $file = $event->getFile(); $request = $event->getRequest(); - + // add a new key to the attribute list $request->attributes->set('grumpy', 'cat'); diff --git a/Tests/Controller/AbstractValidationTest.php b/Tests/Controller/AbstractValidationTest.php index 73d66f9..d0e1e60 100644 --- a/Tests/Controller/AbstractValidationTest.php +++ b/Tests/Controller/AbstractValidationTest.php @@ -11,6 +11,21 @@ abstract class AbstractValidationTest extends AbstractControllerTest abstract protected function getFileWithIncorrectExtension(); abstract protected function getFileWithCorrectMimeType(); abstract protected function getFileWithIncorrectMimeType(); + abstract protected function getOversizedFile(); + + public function testAgainstMaxSize() + { + // assemble a request + $client = $this->client; + $endpoint = $this->helper->endpoint($this->getConfigKey()); + + $client->request('POST', $endpoint, $this->getRequestParameters(), array($this->getOversizedFile())); + $response = $client->getResponse(); + + //$this->assertTrue($response->isNotSuccessful()); + $this->assertEquals($response->headers->get('Content-Type'), 'application/json'); + $this->assertCount(0, $this->getUploadedFiles()); + } public function testAgainstCorrectExtension() { diff --git a/Tests/Controller/BlueimpValidationTest.php b/Tests/Controller/BlueimpValidationTest.php index bdc9493..e2cd6cd 100644 --- a/Tests/Controller/BlueimpValidationTest.php +++ b/Tests/Controller/BlueimpValidationTest.php @@ -17,6 +17,16 @@ class BlueimpValidationTest extends AbstractValidationTest return array(); } + protected function getOversizedFile() + { + return array(new UploadedFile( + $this->createTempFile(512), + 'cat.ok', + 'text/plain', + 512 + )); + } + protected function getFileWithCorrectExtension() { return array(new UploadedFile( diff --git a/Tests/Controller/FancyUploadValidationTest.php b/Tests/Controller/FancyUploadValidationTest.php index 11ef999..7e48964 100644 --- a/Tests/Controller/FancyUploadValidationTest.php +++ b/Tests/Controller/FancyUploadValidationTest.php @@ -17,6 +17,16 @@ class FancyUploadValidationTest extends AbstractValidationTest return array(); } + protected function getOversizedFile() + { + return new UploadedFile( + $this->createTempFile(512), + 'cat.ok', + 'text/plain', + 512 + ); + } + protected function getFileWithCorrectExtension() { return new UploadedFile( diff --git a/Tests/Controller/FineUploaderValidationTest.php b/Tests/Controller/FineUploaderValidationTest.php index 9d5f31c..d1961e4 100644 --- a/Tests/Controller/FineUploaderValidationTest.php +++ b/Tests/Controller/FineUploaderValidationTest.php @@ -17,6 +17,16 @@ class FineUploaderValidationTest extends AbstractValidationTest return array(); } + protected function getOversizedFile() + { + return new UploadedFile( + $this->createTempFile(512), + 'cat.ok', + 'text/plain', + 512 + ); + } + protected function getFileWithCorrectExtension() { return new UploadedFile( diff --git a/Tests/Controller/PluploadValidationTest.php b/Tests/Controller/PluploadValidationTest.php index ccd9848..61ffc55 100644 --- a/Tests/Controller/PluploadValidationTest.php +++ b/Tests/Controller/PluploadValidationTest.php @@ -17,6 +17,16 @@ class PluploadValidationTest extends AbstractValidationTest return array(); } + protected function getOversizedFile() + { + return new UploadedFile( + $this->createTempFile(512), + 'cat.ok', + 'text/plain', + 512 + ); + } + protected function getFileWithCorrectExtension() { return new UploadedFile( diff --git a/Tests/Controller/UploadifyValidationTest.php b/Tests/Controller/UploadifyValidationTest.php index b5851b2..0f10650 100644 --- a/Tests/Controller/UploadifyValidationTest.php +++ b/Tests/Controller/UploadifyValidationTest.php @@ -17,6 +17,16 @@ class UploadifyValidationTest extends AbstractValidationTest return array(); } + protected function getOversizedFile() + { + return new UploadedFile( + $this->createTempFile(512), + 'cat.ok', + 'text/plain', + 512 + ); + } + protected function getFileWithCorrectExtension() { return new UploadedFile( diff --git a/Tests/Controller/YUI3ValidationTest.php b/Tests/Controller/YUI3ValidationTest.php index 3d839f3..ca4919c 100644 --- a/Tests/Controller/YUI3ValidationTest.php +++ b/Tests/Controller/YUI3ValidationTest.php @@ -17,6 +17,16 @@ class YUI3ValidationTest extends AbstractValidationTest return array(); } + protected function getOversizedFile() + { + return new UploadedFile( + $this->createTempFile(512), + 'cat.ok', + 'text/plain', + 512 + ); + } + protected function getFileWithCorrectExtension() { return new UploadedFile(
0
b4de6388ca2a6f23e466685bc8308688851f0bc1
1up-lab/OneupUploaderBundle
Removed controller functions for the previously deleted delete-feature.
commit b4de6388ca2a6f23e466685bc8308688851f0bc1 Author: Jim Schmid <[email protected]> Date: Wed Mar 27 17:53:45 2013 +0100 Removed controller functions for the previously deleted delete-feature. diff --git a/Controller/UploadControllerInterface.php b/Controller/UploadControllerInterface.php index c2631a7..977375e 100644 --- a/Controller/UploadControllerInterface.php +++ b/Controller/UploadControllerInterface.php @@ -5,5 +5,4 @@ namespace Oneup\UploaderBundle\Controller; interface UploadControllerInterface { public function upload(); - public function delete($uuid = null); } \ No newline at end of file diff --git a/Controller/UploaderController.php b/Controller/UploaderController.php index 48aef6e..934de3e 100644 --- a/Controller/UploaderController.php +++ b/Controller/UploaderController.php @@ -60,24 +60,6 @@ class UploaderController implements UploadControllerInterface return new JsonResponse(array('success' => true, 'name' => $name)); } - - public function delete($uuid = null) - { - if(is_null($uuid)) - return new HttpException(400, 'You must provide a file uuid.'); - - $result = $this->storage->remove($this->type, $uuid); - - if($result) - { - $postUploadEvent = new PostDeleteEvent($this->request, $uuid, $this->type); - $this->dispatcher->dispatch(UploadEvents::POST_DELETE, $postUploadEvent); - - return new JsonResponse(array('success' => true)); - } - - return new JsonResponse(array('error' => 'An unknown error occured.')); - } protected function handleUpload(UploadedFile $file) {
0
529b01cac232a81430772f8c5d9ae09f0c1a8d74
1up-lab/OneupUploaderBundle
file tests
commit 529b01cac232a81430772f8c5d9ae09f0c1a8d74 Author: mitom <[email protected]> Date: Fri Oct 11 16:51:37 2013 +0200 file tests diff --git a/Tests/Uploader/File/FileTest.php b/Tests/Uploader/File/FileTest.php new file mode 100644 index 0000000..2753089 --- /dev/null +++ b/Tests/Uploader/File/FileTest.php @@ -0,0 +1,43 @@ +<?php +namespace Oneup\UploaderBundle\Tests\Uploader\File; + +abstract class FileTest extends \PHPUnit_Framework_TestCase +{ + protected $file; + protected $pathname; + protected $path; + protected $basename; + protected $extension; + protected $size; + protected $mimeType; + + public function testGetPathName() + { + $this->assertEquals($this->pathname, $this->file->getPathname()); + } + + public function testGetPath() + { + $this->assertEquals($this->path, $this->file->getPath()); + } + + public function testGetBasename() + { + $this->assertEquals($this->basename, $this->file->getBasename()); + } + + public function testGetExtension() + { + $this->assertEquals($this->extension, $this->file->getExtension()); + } + + public function testGetSize() + { + $this->assertEquals($this->size, $this->file->getSize()); + } + + public function testGetMimeType() + { + $this->assertEquals($this->mimeType, $this->file->getMimeType()); + } +} diff --git a/Tests/Uploader/File/FilesystemFileTest.php b/Tests/Uploader/File/FilesystemFileTest.php new file mode 100644 index 0000000..0868cb9 --- /dev/null +++ b/Tests/Uploader/File/FilesystemFileTest.php @@ -0,0 +1,30 @@ +<?php +namespace Oneup\UploaderBundle\Tests\Uploader\File; + +use Oneup\UploaderBundle\Uploader\File\FilesystemFile; +use Symfony\Component\HttpFoundation\File\UploadedFile; + +class FilesystemFileTest extends FileTest +{ + public function setUp() + { + $this->path = sys_get_temp_dir(). '/oneup_test_tmp'; + mkdir($this->path); + + $this->basename = 'test_file.txt'; + $this->pathname = $this->path .'/'. $this->basename; + $this->extension = 'txt'; + $this->size = 9; //something = 9 bytes + $this->mimeType = 'text/plain'; + + file_put_contents($this->pathname, 'something'); + + $this->file = new FilesystemFile(new UploadedFile($this->pathname, 'test_file.txt', null, null, null, true)); + } + + public function tearDown() + { + unlink($this->pathname); + rmdir($this->path); + } +} diff --git a/Tests/Uploader/File/GaufretteFileTest.php b/Tests/Uploader/File/GaufretteFileTest.php new file mode 100644 index 0000000..fc7e2f7 --- /dev/null +++ b/Tests/Uploader/File/GaufretteFileTest.php @@ -0,0 +1,44 @@ +<?php +namespace Oneup\UploaderBundle\Tests\Uploader\File; + +use Gaufrette\File; +use Gaufrette\StreamWrapper; +use Oneup\UploaderBundle\Uploader\File\GaufretteFile; +use Gaufrette\Adapter\Local as Adapter; +use Gaufrette\Filesystem as GaufretteFileSystem; +use Oneup\UploaderBundle\Uploader\Storage\GaufretteStorage; + +class GaufretteFileTest extends FileTest +{ + public function setUp() + { + $adapter = new Adapter(sys_get_temp_dir(), true); + $filesystem = new GaufretteFilesystem($adapter); + + $map = StreamWrapper::getFilesystemMap(); + $map->set('oneup', $filesystem); + + StreamWrapper::register(); + + $this->storage = new GaufretteStorage($filesystem, 100000); + + $this->path = 'oneup_test_tmp'; + mkdir(sys_get_temp_dir().'/'.$this->path); + + $this->basename = 'test_file.txt'; + $this->pathname = $this->path .'/'. $this->basename; + $this->extension = 'txt'; + $this->size = 9; //something = 9 bytes + $this->mimeType = 'text/plain'; + + file_put_contents(sys_get_temp_dir() .'/' . $this->pathname, 'something'); + + $this->file = new GaufretteFile(new File($this->pathname, $filesystem), $filesystem, 'gaufrette://oneup/'); + } + + public function tearDown() + { + unlink(sys_get_temp_dir().'/'.$this->pathname); + rmdir(sys_get_temp_dir().'/'.$this->path); + } +}
0
8bf36d43c434f4e1ca715f34b4fe116623946db6
1up-lab/OneupUploaderBundle
Added a command to clear orphaned uploads.
commit 8bf36d43c434f4e1ca715f34b4fe116623946db6 Author: Jim Schmid <[email protected]> Date: Tue Mar 12 11:20:26 2013 +0100 Added a command to clear orphaned uploads. diff --git a/Command/ClearOrphansCommand.php b/Command/ClearOrphansCommand.php new file mode 100644 index 0000000..ae80570 --- /dev/null +++ b/Command/ClearOrphansCommand.php @@ -0,0 +1,24 @@ +<?php + +namespace Oneup\UploaderBundle\Command; + +use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\OutputInterface; + +class ClearOrphansCommand extends ContainerAwareCommand +{ + protected function configure() + { + $this + ->setName('oneup:uploader:clear-orphans') + ->setDescription('Clear orphaned uploads according to the max-age you defined in your configuration.') + ; + } + + protected function execute(InputInterface $input, OutputInterface $output) + { + $manager = $this->getContainer()->get('oneup_uploader.orphanage'); + $manager->clear(); + } +} \ No newline at end of file diff --git a/Resources/config/uploader.xml b/Resources/config/uploader.xml index dc79a38..7b85efe 100644 --- a/Resources/config/uploader.xml +++ b/Resources/config/uploader.xml @@ -5,6 +5,7 @@ <parameters> <parameter key="oneup_uploader.chunks.manager.class">Oneup\UploaderBundle\Uploader\Chunk\ChunkManager</parameter> + <parameter key="oneup_uploader.orphanage.class">Oneup\UploaderBundle\Uploader\Orphanage\Orphanage</parameter> <parameter key="oneup_uploader.routing.loader.class">Oneup\UploaderBundle\Routing\RouteLoader</parameter> <parameter key="oneup_uploader.controller.class">Oneup\UploaderBundle\Controller\UploaderController</parameter> </parameters> @@ -13,6 +14,10 @@ <service id="oneup_uploader.chunks.manager" class="%oneup_uploader.chunks.manager.class%"> <argument>%oneup_uploader.chunks%</argument> </service> + + <service id="oneup_uploader.orphanage" class="%oneup_uploader.orphanage.class%"> + <argument>%oneup_uploader.orphanage%</argument> + </service> <!-- controller --> <service id="oneup_uploader.controller" class="%oneup_uploader.controller.class%">
0
ed5ebcf983e514f3d3ee8eae05264b4bae74bdbb
1up-lab/OneupUploaderBundle
Republished event listener, as otherwise they won't be dispatched.
commit ed5ebcf983e514f3d3ee8eae05264b4bae74bdbb Author: Jim Schmid <[email protected]> Date: Mon Apr 22 19:57:32 2013 +0200 Republished event listener, as otherwise they won't be dispatched. diff --git a/Resources/config/validation.xml b/Resources/config/validation.xml index c87a978..3daeb90 100644 --- a/Resources/config/validation.xml +++ b/Resources/config/validation.xml @@ -9,7 +9,6 @@ <service id="oneup_uploader.validation_listener.max_size" class="Oneup\UploaderBundle\EventListener\MaxSizeValidationListener" - public="false" > <tag name="kernel.event_listener" event="oneup_uploader.validation" method="onValidate" /> </service> @@ -17,7 +16,6 @@ <service id="oneup_uploader.validation_listener.allowed_extension" class="Oneup\UploaderBundle\EventListener\AllowedExtensionValidationListener" - public="false" > <tag name="kernel.event_listener" event="oneup_uploader.validation" method="onValidate" /> </service> @@ -25,7 +23,6 @@ <service id="oneup_uploader.validation_listener.disallowed_extension" class="Oneup\UploaderBundle\EventListener\DisallowedExtensionValidationListener" - public="false" > <tag name="kernel.event_listener" event="oneup_uploader.validation" method="onValidate" /> </service>
0
eb7d4d7bea320130d786e075b1f58d4c61da061b
1up-lab/OneupUploaderBundle
Retrieve Storage from injected container.
commit eb7d4d7bea320130d786e075b1f58d4c61da061b Author: Jim Schmid <[email protected]> Date: Tue Mar 12 11:06:50 2013 +0100 Retrieve Storage from injected container. diff --git a/Controller/UploaderController.php b/Controller/UploaderController.php index a511e00..0209311 100644 --- a/Controller/UploaderController.php +++ b/Controller/UploaderController.php @@ -20,5 +20,7 @@ class UploaderController if(!$container->has($config['storage'])) throw new \InvalidArgumentException(sprintf('The storage service "%s" must be defined.')); + + $storage = $container->get($config['storage']); } } \ No newline at end of file
0
a8c1e536657bbee48b0e442067aab1aaf2a9cda6
1up-lab/OneupUploaderBundle
Merge pull request #267 from haeber/fix/typo-in-phpunit-testcase-usage Fixed typo in extends usage of PHPUnit_Framework_TestCase in OrphanageTest
commit a8c1e536657bbee48b0e442067aab1aaf2a9cda6 (from 74099dfe0e4da77cd71d7466f071274d33046c35) Merge: 74099df dd5997e Author: David Greminger <[email protected]> Date: Tue Oct 4 15:57:51 2016 +0200 Merge pull request #267 from haeber/fix/typo-in-phpunit-testcase-usage Fixed typo in extends usage of PHPUnit_Framework_TestCase in OrphanageTest diff --git a/Tests/Uploader/Storage/OrphanageTest.php b/Tests/Uploader/Storage/OrphanageTest.php index ce3f6cd..c539e7f 100644 --- a/Tests/Uploader/Storage/OrphanageTest.php +++ b/Tests/Uploader/Storage/OrphanageTest.php @@ -6,7 +6,7 @@ use Oneup\UploaderBundle\Uploader\Storage\FlysystemOrphanageStorage; use Symfony\Component\Finder\Finder; use Symfony\Component\Filesystem\Filesystem; -abstract class OrphanageTest extends \PHPUnit_Framework_Testcase +abstract class OrphanageTest extends \PHPUnit_Framework_TestCase { protected $tempDirectory; protected $realDirectory; commit a8c1e536657bbee48b0e442067aab1aaf2a9cda6 (from dd5997eaa5a942434f69dad54f7311ac2f483e3a) Merge: 74099df dd5997e Author: David Greminger <[email protected]> Date: Tue Oct 4 15:57:51 2016 +0200 Merge pull request #267 from haeber/fix/typo-in-phpunit-testcase-usage Fixed typo in extends usage of PHPUnit_Framework_TestCase in OrphanageTest diff --git a/README.md b/README.md index d0f6ed6..7f18c9a 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Features included: * Multiple file uploads handled by your chosen frontend library * Chunked uploads -* Supports [Gaufrette](https://github.com/KnpLabs/Gaufrette) and/or local filesystem +* Support for: [Gaufrette](https://github.com/KnpLabs/Gaufrette) / [Flysystem](https://github.com/thephpleague/flysystem) / local filesystem * Provides an orphanage for cleaning up orphaned files * Supports [Session upload progress & cancelation of uploads](http://php.net/manual/en/session.upload-progress.php) as of PHP 5.4 * Fully unit tested diff --git a/Resources/doc/flysystem_storage.md b/Resources/doc/flysystem_storage.md new file mode 100644 index 0000000..76aa1ea --- /dev/null +++ b/Resources/doc/flysystem_storage.md @@ -0,0 +1,75 @@ +Use Flysystem as Storage layer +============================== + +Flysystem is an abstract storage layer you can use to store your uploaded files. An explanation why you should use an abstraction storage layer comes from the _Why use Gaufrette_ section on [the Gaufrette Repo](https://github.com/KnpLabs/Gaufrette): + +> The filesystem abstraction layer permits you to develop your application without the need to know were all those medias will be stored and how. +> +> Another advantage of this is the possibility to update the files location without any impact on the code apart from the definition of your filesystem. In example, if your project grows up very fast and if your server reaches its limits, you can easily move your medias in an Amazon S3 server or any other solution. + +In order to use Flysystem with OneupUploaderBundle, be sure to follow these steps: + +## Install OneupFlysystemBundle + +Add the OneupFlysystemBundle to your composer.json file. + +```js +{ + "require": { + "oneup/flysystem-bundle": "1.4.*" + } +} +``` + +And update your dependencies through composer. + + $> php composer.phar update oneup/flysystem-bundle + +After installing, enable the bundle in your AppKernel: + +``` php +<?php +// app/AppKernel.php + +public function registerBundles() +{ + $bundles = array( + // ... + new Oneup\FlysystemBundle\OneupFlysystemBundle(), + ); +} +``` + +## Configure your Filesystems + +The following is a sample configuration for the OneupFlysystemBundle. It will create a flysystem service called `oneup_flysystem.gallery_filesystem` which can be used in the OneupUploaderBundle. For a complete list of features refer to the [official documentation](https://github.com/1up-lab/OneupFlysystemBundle). + +```yml +# app/config/config.yml + +oneup_flysystem: + adapters: + acme.flysystem_adapter: + awss3v3: + client: acme.s3_client + bucket: ~ + prefix: ~ + filesystems: + gallery: + adapter: acme.flysystem_adapter +``` + +## Configure your mappings + +Activate Flysystem by switching the `type` property to `flysystem` and pass the Flysystem filesystem configured in the previous step. + +```yml +# app/config/config.yml + +oneup_uploader: + mappings: + gallery: + storage: + type: flysystem + filesystem: oneup_flysystem.gallery_filesystem +``` diff --git a/Resources/doc/index.md b/Resources/doc/index.md index 7b6601e..1b07234 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -137,6 +137,7 @@ some more advanced features. * [Return custom data to frontend](response.md) * [Enable chunked uploads](chunked_uploads.md) * [Using the Orphanage](orphanage.md) +* [Use Flysystem as storage layer](flysystem_storage.md) * [Use Gaufrette as storage layer](gaufrette_storage.md) * [Include your own Namer](custom_namer.md) * [Use custom error handlers](custom_error_handler.md)
0
ce5b80993788b053637aa6cad16e50ef703cdd2f
1up-lab/OneupUploaderBundle
Truly useless interface removed.
commit ce5b80993788b053637aa6cad16e50ef703cdd2f Author: Jim Schmid <[email protected]> Date: Fri Apr 5 13:17:55 2013 +0200 Truly useless interface removed. diff --git a/Uploader/Filesystem/FilesystemInterface.php b/Uploader/Filesystem/FilesystemInterface.php deleted file mode 100644 index d648632..0000000 --- a/Uploader/Filesystem/FilesystemInterface.php +++ /dev/null @@ -1,8 +0,0 @@ -<?php - -namespace Oneup\UploaderBundle\Uploader\Filesystem; - -interface FilesystemInterface -{ - public function upload(File $file, $name = null, $path = null); -} \ No newline at end of file
0
fdf8085cf38ee6403626c15c87e09439138d2807
1up-lab/OneupUploaderBundle
Update index.md Changed composer installation version hint from ```*``` to ```dev-master```.
commit fdf8085cf38ee6403626c15c87e09439138d2807 Author: Jim Schmid <[email protected]> Date: Tue Jun 4 10:13:32 2013 +0200 Update index.md Changed composer installation version hint from ```*``` to ```dev-master```. diff --git a/Resources/doc/index.md b/Resources/doc/index.md index 2b6be7a..7e5a2ce 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -34,7 +34,7 @@ Add OneupUploaderBundle to your composer.json using the following construct: ```js { "require": { - "oneup/uploader-bundle": "*" + "oneup/uploader-bundle": "dev-master" } } ```
0
0f30d964784e6bc4a7fd7214af105a5e8f02816e
1up-lab/OneupUploaderBundle
Fix the refactoring as per documentation. use the Twig_SimpleFunction the way as mentioned in the docs http://twig.sensiolabs.org/doc/advanced.html#id2
commit 0f30d964784e6bc4a7fd7214af105a5e8f02816e Author: Ahmad Tawila <[email protected]> Date: Mon Oct 26 18:18:14 2015 +0200 Fix the refactoring as per documentation. use the Twig_SimpleFunction the way as mentioned in the docs http://twig.sensiolabs.org/doc/advanced.html#id2 diff --git a/Twig/Extension/UploaderExtension.php b/Twig/Extension/UploaderExtension.php index ab76375..3cac14d 100644 --- a/Twig/Extension/UploaderExtension.php +++ b/Twig/Extension/UploaderExtension.php @@ -21,11 +21,11 @@ class UploaderExtension extends \Twig_Extension public function getFunctions() { return array( - 'oneup_uploader_endpoint' => new \Twig_SimpleFunction('endpoint', array($this, 'endpoint')), - 'oneup_uploader_progress' => new \Twig_SimpleFunction('progress', array($this, 'progress')), - 'oneup_uploader_cancel' => new \Twig_SimpleFunction('cancel', array($this, 'cancel')), - 'oneup_uploader_upload_key' => new \Twig_SimpleFunction('uploadKey', array($this, 'uploadKey')), - 'oneup_uploader_maxsize' => new \Twig_SimpleFunction('maxSize', array($this, 'maxSize')), + new \Twig_SimpleFunction('oneup_uploader_endpoint', array($this, 'endpoint')), + new \Twig_SimpleFunction('oneup_uploader_progress', array($this, 'progress')), + new \Twig_SimpleFunction('oneup_uploader_cancel', array($this, 'cancel')), + new \Twig_SimpleFunction('oneup_uploader_upload_key', array($this, 'uploadKey')), + new \Twig_SimpleFunction('oneup_uploader_maxsize', array($this, 'maxSize')), ); }
0
9542178a4a4dd1949721ee390f24e004a300f806
1up-lab/OneupUploaderBundle
Added gitignore and excluded composer.lock and vendor directory.
commit 9542178a4a4dd1949721ee390f24e004a300f806 Author: Jim Schmid <[email protected]> Date: Fri Mar 8 18:28:36 2013 +0100 Added gitignore and excluded composer.lock and vendor directory. diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..19982ea --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +composer.lock +vendor \ No newline at end of file
0
3df0636d3dfa53aa4e961f6d9dcee06d21d90f90
1up-lab/OneupUploaderBundle
Register commands to avoid deprecations in Symfony >= 3.4 (#336)
commit 3df0636d3dfa53aa4e961f6d9dcee06d21d90f90 Author: enekochan <[email protected]> Date: Tue May 22 19:05:56 2018 +0200 Register commands to avoid deprecations in Symfony >= 3.4 (#336) diff --git a/Command/ClearChunkCommand.php b/Command/ClearChunkCommand.php index 89660b7..b72bd93 100644 --- a/Command/ClearChunkCommand.php +++ b/Command/ClearChunkCommand.php @@ -8,10 +8,12 @@ use Symfony\Component\Console\Output\OutputInterface; class ClearChunkCommand extends ContainerAwareCommand { + protected static $defaultName = 'oneup:uploader:clear-chunks'; // Make command lazy load + protected function configure() { $this - ->setName('oneup:uploader:clear-chunks') + ->setName(self::$defaultName) // BC with 2.7 ->setDescription('Clear chunks according to the max-age you defined in your configuration.') ; } diff --git a/Command/ClearOrphansCommand.php b/Command/ClearOrphansCommand.php index 9a1b913..a2d44e7 100644 --- a/Command/ClearOrphansCommand.php +++ b/Command/ClearOrphansCommand.php @@ -8,10 +8,12 @@ use Symfony\Component\Console\Output\OutputInterface; class ClearOrphansCommand extends ContainerAwareCommand { + protected static $defaultName = 'oneup:uploader:clear-orphans'; // Make command lazy load + protected function configure() { $this - ->setName('oneup:uploader:clear-orphans') + ->setName(self::$defaultName) // BC with 2.7 ->setDescription('Clear orphaned uploads according to the max-age you defined in your configuration.') ; } diff --git a/Resources/config/uploader.xml b/Resources/config/uploader.xml index 1ab7116..29b3993 100644 --- a/Resources/config/uploader.xml +++ b/Resources/config/uploader.xml @@ -24,6 +24,8 @@ <parameter key="oneup_uploader.controller.mooupload.class">Oneup\UploaderBundle\Controller\MooUploadController</parameter> <parameter key="oneup_uploader.controller.plupload.class">Oneup\UploaderBundle\Controller\PluploadController</parameter> <parameter key="oneup_uploader.controller.dropzone.class">Oneup\UploaderBundle\Controller\DropzoneController</parameter> + <parameter key="oneup_uploader.command.clear_chunks.class">Oneup\UploaderBundle\Command\ClearChunkCommand</parameter> + <parameter key="oneup_uploader.command.clear_orphans.class">Oneup\UploaderBundle\Command\ClearOrphansCommand</parameter> </parameters> <services> @@ -40,7 +42,7 @@ </service> <!-- namer --> - <service id="oneup_uploader.namer.uniqid" class="%oneup_uploader.namer.uniqid.class%" public="true"/> + <service id="oneup_uploader.namer.uniqid" class="%oneup_uploader.namer.uniqid.class%" public="true" /> <service id="oneup_uploader.namer.urlsafe" class="%oneup_uploader.namer.urlsafename.class%" /> <!-- routing --> @@ -49,6 +51,14 @@ <tag name="routing.loader" /> </service> + <!-- commands --> + <service id="oneup_uploader.command.clear_chunks" class="%oneup_uploader.command.clear_chunks.class%"> + <tag name="console.command" command="oneup:uploader:clear-chunks" /> + </service> + <service id="oneup_uploader.command.clear_orphans" class="%oneup_uploader.command.clear_orphans.class%"> + <tag name="console.command" command="oneup:uploader:clear-orphans" /> + </service> + </services> </container>
0
a882e445bafa6d15e1b2a5956984b8c1b733d47e
1up-lab/OneupUploaderBundle
Removed old ValidationTests. Need to be reintroduced.
commit a882e445bafa6d15e1b2a5956984b8c1b733d47e Author: Jim Schmid <[email protected]> Date: Mon Apr 22 19:16:17 2013 +0200 Removed old ValidationTests. Need to be reintroduced. diff --git a/Tests/Controller/AbstractControllerValidationTest.php b/Tests/Controller/AbstractControllerValidationTest.php deleted file mode 100644 index 348c7a2..0000000 --- a/Tests/Controller/AbstractControllerValidationTest.php +++ /dev/null @@ -1,167 +0,0 @@ -<?php - -namespace Oneup\UploaderBundle\Tests\Controller; - -abstract class AbstractControllerValidationTest extends \PHPUnit_Framework_TestCase -{ - abstract public function getControllerString(); - - /** - * @expectedException Symfony\Component\HttpFoundation\File\Exception\UploadException - */ - public function testMaxSizeValidationFails() - { - // create a config - $config = array(); - $config['max_size'] = 10; - $config['allowed_extensions'] = array(); - $config['disallowed_extensions'] = array(); - - $this->performConfigTest($config); - } - - public function testMaxSizeValidationPasses() - { - // create a config - $config = array(); - $config['max_size'] = 20; - $config['allowed_extensions'] = array(); - $config['disallowed_extensions'] = array(); - - $this->performConfigTest($config); - } - - /** - * @expectedException Symfony\Component\HttpFoundation\File\Exception\UploadException - */ - public function testAllowedExtensionValidationFails() - { - // create a config - $config = array(); - $config['max_size'] = 20; - $config['allowed_extensions'] = array('txt', 'pdf'); - $config['disallowed_extensions'] = array(); - - $this->performConfigTest($config); - } - - public function testAllowedExtensionValidationPasses() - { - // create a config - $config = array(); - $config['max_size'] = 20; - $config['allowed_extensions'] = array('png', 'jpg', 'jpeg', 'gif'); - $config['disallowed_extensions'] = array(); - - $this->performConfigTest($config); - } - - /** - * @expectedException Symfony\Component\HttpFoundation\File\Exception\UploadException - */ - public function testDisallowedExtensionValidationFails() - { - // create a config - $config = array(); - $config['max_size'] = 20; - $config['allowed_extensions'] = array(); - $config['disallowed_extensions'] = array('jpeg'); - - $this->performConfigTest($config); - } - - public function testDisallowedExtensionValidationPasses() - { - // create a config - $config = array(); - $config['max_size'] = 20; - $config['allowed_extensions'] = array(); - $config['disallowed_extensions'] = array('exe', 'bat'); - - $this->performConfigTest($config); - } - - protected function performConfigTest($config) - { - // prepare mock - $file = $this->getUploadedFileMock(); - $method = $this->getValidationMethod(); - - $container = $this->getContainerMock(); - $storage = $this->getStorageMock(); - - $str = $this->getControllerString(); - $controller = new $str($container, $storage, $config, 'cat'); - $method->invoke($controller, $file); - - // yey, no exception thrown - $this->assertTrue(true); - } - - protected function getUploadedFileMock() - { - $file = $this->getMockBuilder('Symfony\Component\HttpFoundation\File\UploadedFile') - ->disableOriginalConstructor() - ->getMock() - ; - - $file - ->expects($this->any()) - ->method('getClientSize') - ->will($this->returnValue(15)) - ; - - $file - ->expects($this->any()) - ->method('getClientOriginalName') - ->will($this->returnValue('grumpycat.jpeg')) - ; - - return $file; - } - - protected function getContainerMock() - { - $mock = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface'); - $mock - ->expects($this->any()) - ->method('get') - ->will($this->returnCallback(array($this, 'containerGetCb'))) - ; - - return $mock; - } - - public function containerGetCb($inp) - { - if($inp == 'event_dispatcher') - return $this->getEventDispatcherMock(); - } - - protected function getEventDispatcherMock() - { - $mock = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface'); - $mock - ->expects($this->any()) - ->method('dispatch') - ->will($this->returnValue(true)) - ; - - return $mock; - } - - protected function getStorageMock() - { - return $this->getMock('Oneup\UploaderBundle\Uploader\Storage\StorageInterface'); - } - - protected function getValidationMethod() - { - // create a public version of the validate method - $class = new \ReflectionClass($this->getControllerString()); - $method = $class->getMethod('validate'); - $method->setAccessible(true); - - return $method; - } -} \ No newline at end of file diff --git a/Tests/Controller/BlueimpControllerValidationTest.php b/Tests/Controller/BlueimpControllerValidationTest.php deleted file mode 100644 index 40a32eb..0000000 --- a/Tests/Controller/BlueimpControllerValidationTest.php +++ /dev/null @@ -1,13 +0,0 @@ -<?php - -namespace Oneup\UploaderBundle\Tests\Controller; - -use Oneup\UploaderBundle\Tests\Controller\AbstractControllerValidationTest; - -class BlueimpControllerValidationTest extends AbstractControllerValidationTest -{ - public function getControllerString() - { - return 'Oneup\UploaderBundle\Controller\BlueimpController'; - } -} \ No newline at end of file diff --git a/Tests/Controller/FineUploaderControllerValidationTest.php b/Tests/Controller/FineUploaderControllerValidationTest.php deleted file mode 100644 index 3c1f2c9..0000000 --- a/Tests/Controller/FineUploaderControllerValidationTest.php +++ /dev/null @@ -1,13 +0,0 @@ -<?php - -namespace Oneup\UploaderBundle\Tests\Controller; - -use Oneup\UploaderBundle\Tests\Controller\AbstractControllerValidationTest; - -class FineUploaderControllerValidationTest extends AbstractControllerValidationTest -{ - public function getControllerString() - { - return 'Oneup\UploaderBundle\Controller\FineUploaderController'; - } -} \ No newline at end of file
0
f3d5507675fa0b56410bbaf219678087170fa7ea
1up-lab/OneupUploaderBundle
Added a Controller, registered it as a Service and made it configurable through configuration.
commit f3d5507675fa0b56410bbaf219678087170fa7ea Author: Jim Schmid <[email protected]> Date: Mon Mar 11 18:54:04 2013 +0100 Added a Controller, registered it as a Service and made it configurable through configuration. diff --git a/Controller/UploaderController.php b/Controller/UploaderController.php new file mode 100644 index 0000000..c33e281 --- /dev/null +++ b/Controller/UploaderController.php @@ -0,0 +1,18 @@ +<?php + +namespace Oneup\UploaderBundle\Controller; + +class UploaderController +{ + protected $mappings; + + public function __construct($mappings) + { + $this->mappings = $mappings; + } + + public function upload($mapping) + { + + } +} \ No newline at end of file diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index 9cbdc10..7900b4e 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -17,8 +17,8 @@ class Configuration implements ConfigurationInterface ->arrayNode('routing') ->addDefaultsIfNotSet() ->children() - ->scalarNode('prefix')->defaultValue('/oneup/uploader')->end() - ->scalarNode('action')->defaultValue('OneupUploaderBundle:Uploader:upload')->end() + ->scalarNode('name')->defaultValue('/_uploader')->end() + ->scalarNode('action')->defaultValue('oneup_uploader.controller:upload')->end() ->end() ->end() ->arrayNode('chunks') @@ -34,8 +34,9 @@ class Configuration implements ConfigurationInterface ->requiresAtLeastOneElement() ->prototype('array') ->children() - ->scalarNode('namer')->defaultNull()->end() ->scalarNode('storage')->isRequired()->end() + ->scalarNode('action')->defaultNull()->end() + ->scalarNode('namer')->defaultNull()->end() ->end() ->end() ->end() diff --git a/Resources/config/uploader.xml b/Resources/config/uploader.xml index 727e452..e440170 100644 --- a/Resources/config/uploader.xml +++ b/Resources/config/uploader.xml @@ -6,6 +6,7 @@ <parameters> <parameter key="oneup_uploader.chunks.manager.class">Oneup\UploaderBundle\Uploader\Chunk\ChunkManager</parameter> <parameter key="oneup_uploader.routing.loader.class">Oneup\UploaderBundle\Routing\RouteLoader</parameter> + <parameter key="oneup_uploader.controller.class">Oneup\UploaderBundle\Controller\UploaderController</parameter> </parameters> <services> @@ -13,9 +14,15 @@ <argument>%oneup_uploader.chunks%</argument> </service> + <!-- controller --> + <service id="oneup_uploader.controller" class="%oneup_uploader.controller.class%"> + <argument>%oneup_uploader.mappings%</argument> + </service> + + <!-- routing --> <service id="oneup_uploader.routing.loader" class="%oneup_uploader.routing.loader.class%"> <argument>%oneup_uploader.routing.action%</argument> - <argument>%oneup_uploader.routing.prefix%</argument> + <argument>%oneup_uploader.routing.name%</argument> <argument>%oneup_uploader.mappings%</argument> <tag name="routing.loader" /> diff --git a/Routing/RouteLoader.php b/Routing/RouteLoader.php index 7c6ef11..881e0d9 100644 --- a/Routing/RouteLoader.php +++ b/Routing/RouteLoader.php @@ -12,10 +12,10 @@ class RouteLoader extends Loader protected $prefix; protected $mappings; - public function __construct($action, $prefix, array $mappings) + public function __construct($action, $name, array $mappings) { + $this->name = $name; $this->action = $action; - $this->prefix = $prefix; $this->mappings = $mappings; } @@ -27,16 +27,17 @@ class RouteLoader extends Loader public function load($resource, $type = null) { $requirements = array('_method' => 'POST', 'mapping' => '[A-z0-9_\-]*'); - $defaults = array('_controller' => $this->action); - $routes = new RouteCollection(); foreach($this->mappings as $key => $mapping) { - $defaults += array('mapping' => $key); + $defaults = array( + '_controller' => is_null($mapping['action']) ? $this->action : $mapping['action'], + 'mapping' => $key + ); $routes->add(sprintf('_uploader_%s', $key), new Route( - sprintf('%s/{mapping}', $this->prefix), + sprintf('%s/{mapping}', $this->name), $defaults, $requirements, array()
0
402976688c97e35a696f133a729732ac726d7666
1up-lab/OneupUploaderBundle
CS fixes for Uploader
commit 402976688c97e35a696f133a729732ac726d7666 Author: Jim Schmid <[email protected]> Date: Thu Jun 20 21:24:34 2013 +0200 CS fixes for Uploader diff --git a/Uploader/Chunk/ChunkManager.php b/Uploader/Chunk/ChunkManager.php index 14f070e..b1dcf23 100644 --- a/Uploader/Chunk/ChunkManager.php +++ b/Uploader/Chunk/ChunkManager.php @@ -7,7 +7,6 @@ use Symfony\Component\Finder\Finder; use Symfony\Component\Filesystem\Filesystem; use Oneup\UploaderBundle\Uploader\Chunk\ChunkManagerInterface; -use Oneup\UploaderBundle\Uploader\Naming\NamerInterface; class ChunkManager implements ChunkManagerInterface { @@ -15,43 +14,39 @@ class ChunkManager implements ChunkManagerInterface { $this->configuration = $configuration; } - + public function clear() { $system = new Filesystem(); $finder = new Finder(); - - try - { + + try { $finder->in($this->configuration['directory'])->date('<=' . -1 * (int) $this->configuration['maxage'] . 'seconds')->files(); - } - catch(\InvalidArgumentException $e) - { + } catch (\InvalidArgumentException $e) { // the finder will throw an exception of type InvalidArgumentException // if the directory he should search in does not exist // in that case we don't have anything to clean return; } - - foreach($finder as $file) - { + + foreach ($finder as $file) { $system->remove($file); } } - + public function addChunk($uuid, $index, UploadedFile $chunk, $original) { $filesystem = new Filesystem(); $path = sprintf('%s/%s', $this->configuration['directory'], $uuid); $name = sprintf('%s_%s', $index, $original); - + // create directory if it does not yet exist if(!$filesystem->exists($path)) $filesystem->mkdir(sprintf('%s/%s', $this->configuration['directory'], $uuid)); - + return $chunk->move($path, $name); } - + public function assembleChunks(\Traversable $chunks) { // I don't really get it why getIterator()->current() always @@ -59,34 +54,32 @@ class ChunkManager implements ChunkManagerInterface // in a rather unorthodox way. $i = 0; $base = null; - - foreach($chunks as $file) - { - if($i++ == 0) - { + + foreach ($chunks as $file) { + if ($i++ == 0) { $base = $file; - + // proceed with next files, as we have our // base data-container continue; } - + if(false === file_put_contents($base->getPathname(), file_get_contents($file->getPathname()), \FILE_APPEND | \LOCK_EX)) throw new \RuntimeException('Reassembling chunks failed.'); } - + return $base; } - + public function cleanup($path) { // cleanup $filesystem = new Filesystem(); $filesystem->remove($path); - + return true; } - + public function getChunks($uuid) { $finder = new Finder(); @@ -96,10 +89,10 @@ class ChunkManager implements ChunkManagerInterface $s = explode('_', $b->getBasename()); $t = (int) $t[0]; $s = (int) $s[0]; - + return $s < $t; }); - + return $finder; } -} \ No newline at end of file +} diff --git a/Uploader/Chunk/ChunkManagerInterface.php b/Uploader/Chunk/ChunkManagerInterface.php index f0059bb..009bfed 100644 --- a/Uploader/Chunk/ChunkManagerInterface.php +++ b/Uploader/Chunk/ChunkManagerInterface.php @@ -11,4 +11,4 @@ interface ChunkManagerInterface public function assembleChunks(\Traversable $chunks); public function cleanup($path); public function getChunks($uuid); -} \ No newline at end of file +} diff --git a/Uploader/Exception/ValidationException.php b/Uploader/Exception/ValidationException.php index ced7379..6d632f1 100644 --- a/Uploader/Exception/ValidationException.php +++ b/Uploader/Exception/ValidationException.php @@ -4,5 +4,5 @@ namespace Oneup\UploaderBundle\Uploader\Exception; class ValidationException extends \DomainException { - -} \ No newline at end of file + +} diff --git a/Uploader/Naming/NamerInterface.php b/Uploader/Naming/NamerInterface.php index cf6fa30..40ba4cd 100644 --- a/Uploader/Naming/NamerInterface.php +++ b/Uploader/Naming/NamerInterface.php @@ -7,4 +7,4 @@ use Symfony\Component\HttpFoundation\File\UploadedFile; interface NamerInterface { public function name(UploadedFile $file); -} \ No newline at end of file +} diff --git a/Uploader/Naming/UniqidNamer.php b/Uploader/Naming/UniqidNamer.php index af408d2..4c16b98 100644 --- a/Uploader/Naming/UniqidNamer.php +++ b/Uploader/Naming/UniqidNamer.php @@ -11,4 +11,4 @@ class UniqidNamer implements NamerInterface { return sprintf('%s.%s', uniqid(), $file->guessExtension()); } -} \ No newline at end of file +} diff --git a/Uploader/Orphanage/OrphanageManager.php b/Uploader/Orphanage/OrphanageManager.php index 053200f..b09dd25 100644 --- a/Uploader/Orphanage/OrphanageManager.php +++ b/Uploader/Orphanage/OrphanageManager.php @@ -10,38 +10,34 @@ class OrphanageManager { protected $config; protected $container; - + public function __construct(ContainerInterface $container, array $config) { $this->container = $container; $this->config = $config; } - + public function get($key) { return $this->container->get(sprintf('oneup_uploader.orphanage.%s', $key)); } - + public function clear() { $system = new Filesystem(); $finder = new Finder(); - - try - { + + try { $finder->in($this->config['directory'])->date('<=' . -1 * (int) $this->config['maxage'] . 'seconds')->files(); - } - catch(\InvalidArgumentException $e) - { + } catch (\InvalidArgumentException $e) { // the finder will throw an exception of type InvalidArgumentException // if the directory he should search in does not exist // in that case we don't have anything to clean return; } - - foreach($finder as $file) - { + + foreach ($finder as $file) { $system->remove($file); } } -} \ No newline at end of file +} diff --git a/Uploader/Response/AbstractResponse.php b/Uploader/Response/AbstractResponse.php index 11f67f7..561c7b7 100644 --- a/Uploader/Response/AbstractResponse.php +++ b/Uploader/Response/AbstractResponse.php @@ -7,7 +7,7 @@ use Oneup\UploaderBundle\Uploader\Response\ResponseInterface; abstract class AbstractResponse implements \ArrayAccess, ResponseInterface { protected $data; - + public function __construct() { $this->data = array(); @@ -17,19 +17,19 @@ abstract class AbstractResponse implements \ArrayAccess, ResponseInterface { is_null($offset) ? $this->data[] = $value : $this->data[$offset] = $value; } - + public function offsetExists($offset) { return isset($this->data[$offset]); } - + public function offsetUnset($offset) { unset($this->data[$offset]); } - + public function offsetGet($offset) { return isset($this->data[$offset]) ? $this->data[$offset] : null; } -} \ No newline at end of file +} diff --git a/Uploader/Response/EmptyResponse.php b/Uploader/Response/EmptyResponse.php index de61b42..0258586 100644 --- a/Uploader/Response/EmptyResponse.php +++ b/Uploader/Response/EmptyResponse.php @@ -5,9 +5,9 @@ namespace Oneup\UploaderBundle\Uploader\Response; use Oneup\UploaderBundle\Uploader\Response\AbstractResponse; class EmptyResponse extends AbstractResponse -{ +{ public function assemble() { return $this->data; } -} \ No newline at end of file +} diff --git a/Uploader/Response/FineUploaderResponse.php b/Uploader/Response/FineUploaderResponse.php index 4b47e3c..52c8570 100644 --- a/Uploader/Response/FineUploaderResponse.php +++ b/Uploader/Response/FineUploaderResponse.php @@ -8,15 +8,15 @@ class FineUploaderResponse extends AbstractResponse { protected $success; protected $error; - + public function __construct() { $this->success = true; $this->error = null; - + parent::__construct(); } - + public function assemble() { // explicitly overwrite success and error key @@ -24,37 +24,37 @@ class FineUploaderResponse extends AbstractResponse // frontend uploader $data = $this->data; $data['success'] = $this->success; - + if($this->success) unset($data['error']); - + if(!$this->success) $data['error'] = $this->error; - + return $data; } - + public function setSuccess($success) { $this->success = (bool) $success; - + return $this; } - + public function getSuccess() { return $this->success; } - + public function setError($msg) { $this->error = $msg; - + return $this; } - + public function getError() { return $this->error; } -} \ No newline at end of file +} diff --git a/Uploader/Response/MooUploadResponse.php b/Uploader/Response/MooUploadResponse.php index 44e0db4..bcb17b6 100644 --- a/Uploader/Response/MooUploadResponse.php +++ b/Uploader/Response/MooUploadResponse.php @@ -12,98 +12,98 @@ class MooUploadResponse extends AbstractResponse protected $error; protected $finish; protected $uploadedName; - + public function __construct() { $this->finish = true; $this->error = 0; - + parent::__construct(); } - + public function assemble() { $data = $this->data; - + $data['id'] = $this->id; $data['name'] = $this->name; $data['size'] = $this->size; $data['error'] = $this->error; $data['finish'] = $this->finish; $data['upload_name'] = $this->uploadedName; - + return $data; } - + public function setId($id) { $this->id = $id; - + return $this; } - + public function getId() { return $this->id; } - + public function setName($name) { $this->name = $name; - + return $this; } - + public function getName() { return $this->name; } - + public function setSize($size) { $this->size = $size; - + return $this; } - + public function getSize() { return $this->size; } - + public function setError($error) { $this->error = $error; - + return $this; } - + public function getError() { return $this->error; } - + public function setFinish($finish) { $this->finish = $finish; - + return $this; } - + public function getFinish() { return $this->finish; } - + public function setUploadedName($name) { $this->uploadedName = $name; - + return $this; } - + public function getUploadedName() { return $this->uploadedName; } -} \ No newline at end of file +} diff --git a/Uploader/Response/ResponseInterface.php b/Uploader/Response/ResponseInterface.php index 65fe303..135ef3a 100644 --- a/Uploader/Response/ResponseInterface.php +++ b/Uploader/Response/ResponseInterface.php @@ -5,4 +5,4 @@ namespace Oneup\UploaderBundle\Uploader\Response; interface ResponseInterface { public function assemble(); -} \ No newline at end of file +} diff --git a/Uploader/Storage/FilesystemStorage.php b/Uploader/Storage/FilesystemStorage.php index 4d52bb9..ed7931e 100644 --- a/Uploader/Storage/FilesystemStorage.php +++ b/Uploader/Storage/FilesystemStorage.php @@ -10,26 +10,26 @@ use Oneup\UploaderBundle\Uploader\Storage\StorageInterface; class FilesystemStorage implements StorageInterface { protected $directory; - + public function __construct($directory) { $this->directory = $directory; } - + public function upload(File $file, $name, $path = null) { $filesystem = new Filesystem(); - + $path = is_null($path) ? $name : sprintf('%s/%s', $path, $name); $path = sprintf('%s/%s', $this->directory, $path); - + // now that we have the correct path, compute the correct name // and target directory $targetName = basename($path); $targetDir = dirname($path); - + $file = $file->move($targetDir, $targetName); - + return $file; } -} \ No newline at end of file +} diff --git a/Uploader/Storage/GaufretteStorage.php b/Uploader/Storage/GaufretteStorage.php index 47306ab..ea8a6b3 100644 --- a/Uploader/Storage/GaufretteStorage.php +++ b/Uploader/Storage/GaufretteStorage.php @@ -13,42 +13,40 @@ use Oneup\UploaderBundle\Uploader\Storage\StorageInterface; class GaufretteStorage implements StorageInterface { protected $filesystem; - + public function __construct(Filesystem $filesystem) { $this->filesystem = $filesystem; } - + public function upload(File $file, $name, $path = null) { $path = is_null($path) ? $name : sprintf('%s/%s', $path, $name); - - if($this->filesystem->getAdapter() instanceof MetadataSupporter) - { + + if ($this->filesystem->getAdapter() instanceof MetadataSupporter) { $this->filesystem->getAdapter()->setMetadata($name, array('contentType' => $file->getMimeType())); } - + $src = new LocalStream($file->getPathname()); $dst = $this->filesystem->createStream($path); - + // this is a somehow ugly workaround introduced // because the stream-mode is not able to create // subdirectories. if(!$this->filesystem->has($path)) $this->filesystem->write($path, '', true); - + $src->open(new StreamMode('rb+')); $dst->open(new StreamMode('wb+')); - - while(!$src->eof()) - { + + while (!$src->eof()) { $data = $src->read(100000); $written = $dst->write($data); } - + $dst->close(); $src->close(); - + return $this->filesystem->get($path); } -} \ No newline at end of file +} diff --git a/Uploader/Storage/OrphanageStorage.php b/Uploader/Storage/OrphanageStorage.php index 1248f1c..38c4e96 100644 --- a/Uploader/Storage/OrphanageStorage.php +++ b/Uploader/Storage/OrphanageStorage.php @@ -17,62 +17,58 @@ class OrphanageStorage extends FilesystemStorage implements OrphanageStorageInte protected $session; protected $config; protected $type; - + public function __construct(StorageInterface $storage, SessionInterface $session, $config, $type) { parent::__construct($config['directory']); - + $this->storage = $storage; $this->session = $session; $this->config = $config; $this->type = $type; } - + public function upload(File $file, $name, $path = null) { if(!$this->session->isStarted()) throw new \RuntimeException('You need a running session in order to run the Orphanage.'); - + return parent::upload($file, $name, $this->getPath()); } - + public function uploadFiles() { $filesystem = new Filesystem(); - - try - { + + try { $files = $this->getFiles(); $return = array(); - - foreach($files as $file) - { + + foreach ($files as $file) { $return[] = $this->storage->upload(new File($file->getPathname()), str_replace($this->getFindPath(), '', $file)); } return $return; - } - catch(\Exception $e) - { + } catch (\Exception $e) { return array(); } } - + protected function getFiles() { $finder = new Finder(); $finder->in($this->getFindPath())->files(); - + return $finder; } - + protected function getPath() { return sprintf('%s/%s', $this->session->getId(), $this->type); } - + protected function getFindPath() { return sprintf('%s/%s', $this->config['directory'], $this->getPath()); } -} \ No newline at end of file +} diff --git a/Uploader/Storage/StorageInterface.php b/Uploader/Storage/StorageInterface.php index e4e3dce..090db1a 100644 --- a/Uploader/Storage/StorageInterface.php +++ b/Uploader/Storage/StorageInterface.php @@ -7,4 +7,4 @@ use Symfony\Component\HttpFoundation\File\File; interface StorageInterface { public function upload(File $file, $name, $path = null); -} \ No newline at end of file +}
0
31505714ccb8002e9758545116dfb869d17d738d
1up-lab/OneupUploaderBundle
minor: fix service name in yml definition ```app.upload_listener``` instead of ```acme_hello.upload_listener```
commit 31505714ccb8002e9758545116dfb869d17d738d Author: Robert Freigang <[email protected]> Date: Tue Nov 7 07:36:16 2017 +0100 minor: fix service name in yml definition ```app.upload_listener``` instead of ```acme_hello.upload_listener``` diff --git a/Resources/doc/custom_logic.md b/Resources/doc/custom_logic.md index 3471492..421b66a 100644 --- a/Resources/doc/custom_logic.md +++ b/Resources/doc/custom_logic.md @@ -53,7 +53,7 @@ And register it in your `services.xml`. ```yml services: - acme_hello.upload_listener: + app.upload_listener: class: AppBundle\EventListener\UploadListener arguments: ["@doctrine.orm.entity_manager"] tags:
0
254d5cdb0d6f17475afe5a2c8739f7387496ace1
1up-lab/OneupUploaderBundle
Added a template helper and a twig function to get to the endpoint route of a mapping.
commit 254d5cdb0d6f17475afe5a2c8739f7387496ace1 Author: Jim Schmid <[email protected]> Date: Fri Apr 12 18:11:56 2013 +0200 Added a template helper and a twig function to get to the endpoint route of a mapping. diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index da81832..89051cd 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -28,6 +28,7 @@ class Configuration implements ConfigurationInterface ->scalarNode('directory')->defaultNull()->end() ->end() ->end() + ->scalarNode('twig')->defaultTrue()->end() ->arrayNode('mappings') ->useAttributeAsKey('id') ->isRequired() diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index f643686..bf0121f 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -21,6 +21,12 @@ class OneupUploaderExtension extends Extension $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('uploader.xml'); + $loader->load('templating.xml'); + + if($config['twig']) + { + $loader->load('twig.xml'); + } $config['chunks']['directory'] = is_null($config['chunks']['directory']) ? sprintf('%s/uploader/chunks', $container->getParameter('kernel.cache_dir')) : diff --git a/Resources/config/templating.xml b/Resources/config/templating.xml new file mode 100644 index 0000000..4593804 --- /dev/null +++ b/Resources/config/templating.xml @@ -0,0 +1,16 @@ +<?xml version="1.0" encoding="UTF-8" ?> + +<container xmlns="http://symfony.com/schema/dic/services" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"> + + <services> + + <service id="oneup_uploader.templating.uploader_helper" class="Oneup\UploaderBundle\Templating\Helper\UploaderHelper"> + <argument type="service" id="router" /> + <tag name="templating.helper" alias="oneup_uploader" /> + </service> + + </services> + +</container> \ No newline at end of file diff --git a/Resources/config/twig.xml b/Resources/config/twig.xml new file mode 100644 index 0000000..95c0c2d --- /dev/null +++ b/Resources/config/twig.xml @@ -0,0 +1,16 @@ +<?xml version="1.0" encoding="UTF-8" ?> + +<container xmlns="http://symfony.com/schema/dic/services" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"> + + <services> + + <service id="oneup_uploader.twig.extension.uploader" class="Oneup\UploaderBundle\Twig\Extension\UploaderExtension" public="true"> + <argument type="service" id="oneup_uploader.templating.uploader_helper" /> + <tag name="twig.extension" /> + </service> + + </services> + +</container> \ No newline at end of file diff --git a/Templating/Helper/UploaderHelper.php b/Templating/Helper/UploaderHelper.php new file mode 100644 index 0000000..b5c376a --- /dev/null +++ b/Templating/Helper/UploaderHelper.php @@ -0,0 +1,26 @@ +<?php + +namespace Oneup\UploaderBundle\Templating\Helper; + +use Symfony\Component\Routing\RouterInterface; +use Symfony\Component\Templating\Helper\Helper; + +class UploaderHelper extends Helper +{ + protected $router; + + public function __construct(RouterInterface $router) + { + $this->router = $router; + } + + public function getName() + { + return 'oneup_uploader'; + } + + public function endpoint($key) + { + return $this->router->generate(sprintf('_uploader_%s', $key)); + } +} \ No newline at end of file diff --git a/Twig/Extension/UploaderExtension.php b/Twig/Extension/UploaderExtension.php new file mode 100644 index 0000000..910a0f9 --- /dev/null +++ b/Twig/Extension/UploaderExtension.php @@ -0,0 +1,30 @@ +<?php + +namespace Oneup\UploaderBundle\Twig\Extension; + +use Oneup\UploaderBundle\Templating\Helper\UploaderHelper; + +class UploaderExtension extends \Twig_Extension +{ + protected $helper; + + public function __construct(UploaderHelper $helper) + { + $this->helper = $helper; + } + + public function getName() + { + return 'oneup_uploader'; + } + + public function getFunctions() + { + return array('oneup_uploader_endpoint' => new \Twig_Function_Method($this, 'endpoint')); + } + + public function endpoint($key) + { + return $this->helper->endpoint($key); + } +} \ No newline at end of file
0
91e11e6f62978a420e8ccceb2bae0f2e6993416b
1up-lab/OneupUploaderBundle
Create PluploadErrorHandler.php
commit 91e11e6f62978a420e8ccceb2bae0f2e6993416b Author: MJBGO <[email protected]> Date: Sun Nov 16 00:01:36 2014 +0100 Create PluploadErrorHandler.php diff --git a/Uploader/ErrorHandler/PluploadErrorHandler.php b/Uploader/ErrorHandler/PluploadErrorHandler.php new file mode 100644 index 0000000..6716c87 --- /dev/null +++ b/Uploader/ErrorHandler/PluploadErrorHandler.php @@ -0,0 +1,19 @@ +<?php + +namespace Oneup\UploaderBundle\Uploader\ErrorHandler; + +use Exception; +use Oneup\UploaderBundle\Uploader\ErrorHandler\ErrorHandlerInterface; +use Oneup\UploaderBundle\Uploader\Response\AbstractResponse; + +class PluploadErrorHandler implements ErrorHandlerInterface +{ + public function addException(AbstractResponse $response, Exception $exception) + { + /* Plupload only needs an error message so it can be handled client side */ + $message = $exception->getMessage(); + $response['error'] = $message; + } +} + +?>
0
5979d57962b6ff4c54cfd1aba8e2c2dca1cf2e9c
1up-lab/OneupUploaderBundle
Implemented chunked uploads for Blueimp frontend.
commit 5979d57962b6ff4c54cfd1aba8e2c2dca1cf2e9c Author: Jim Schmid <[email protected]> Date: Tue Apr 9 22:50:07 2013 +0200 Implemented chunked uploads for Blueimp frontend. diff --git a/Controller/BlueimpController.php b/Controller/BlueimpController.php index 9181860..c9b6286 100644 --- a/Controller/BlueimpController.php +++ b/Controller/BlueimpController.php @@ -12,7 +12,7 @@ use Oneup\UploaderBundle\Event\PostPersistEvent; use Oneup\UploaderBundle\Event\PostUploadEvent; use Oneup\UploaderBundle\Controller\UploadControllerInterface; use Oneup\UploaderBundle\Uploader\Storage\StorageInterface; -use Oneup\UploaderBundle\Uploader\Response\BlueimpResponse; +use Oneup\UploaderBundle\Uploader\Response\EmptyResponse; class BlueimpController implements UploadControllerInterface { @@ -35,16 +35,18 @@ class BlueimpController implements UploadControllerInterface $dispatcher = $this->container->get('event_dispatcher'); $translator = $this->container->get('translator'); - $response = new BlueimpResponse(); + $response = new EmptyResponse(); $files = $request->files; + $chunked = !is_null($request->headers->get('content-range')); + foreach($files as $file) { $file = $file[0]; try { - $uploaded = $this->handleUpload($file); + $uploaded = $chunked ? $this->handleChunkedUpload($file) : $this->handleUpload($file); $postUploadEvent = new PostUploadEvent($uploaded, $response, $request, $this->type, $this->config); $dispatcher->dispatch(UploadEvents::POST_UPLOAD, $postUploadEvent); @@ -83,6 +85,66 @@ class BlueimpController implements UploadControllerInterface return $uploaded; } + protected function handleChunkedUpload(UploadedFile $file) + { + $request = $this->container->get('request'); + $session = $this->container->get('session'); + $chunkManager = $this->container->get('oneup_uploader.chunk_manager'); + $headerRange = $request->headers->get('content-range'); + $attachmentName = rawurldecode(preg_replace('/(^[^"]+")|("$)/', '', $request->headers->get('content-disposition'))); + + // split the header string to the appropriate parts + list($tmp, $startByte, $endByte, $totalBytes) = preg_split('/[^0-9]+/', $headerRange); + + $uploaded = null; + + // getting information about chunks + // note: We don't have a chance to get the last $total + // correct. This is due to the fact that the $size variable + // is incorrect. As it will always be a higher number than + // the one before, we just let that happen, if you have + // any idea to fix this without fetching information about + // previously saved files, let me know. + $size = ($endByte + 1 - $startByte); + $last = ($endByte + 1) == $totalBytes; + $index = $last ? \PHP_INT_MAX : floor($startByte / $size); + $total = ceil($totalBytes / $size); + + // it is possible, that two clients send a file with the + // exact same filename, therefore we have to add the session + // to the uuid otherwise we will get a mess + $uuid = md5(sprintf('%s.%s', $attachmentName, $session->getId())); + $orig = $attachmentName; + + $chunkManager->addChunk($uuid, $index, $file, $orig); + + // if all chunks collected and stored, proceed + // with reassembling the parts + if(($endByte + 1) == $totalBytes) + { + // we'll take the first chunk and append the others to it + // this way we don't need another file in temporary space for assembling + $chunks = $chunkManager->getChunks($uuid); + + // assemble parts + $assembled = $chunkManager->assembleChunks($chunks); + $path = $assembled->getPath(); + + // create a temporary uploaded file to meet the interface restrictions + $uploadedFile = new UploadedFile($assembled->getPathname(), $assembled->getBasename(), null, null, null, true); + + // validate this entity and upload on success + $this->validate($uploadedFile); + $uploaded = $this->handleUpload($uploadedFile); + + $chunkManager->cleanup($path); + } + + return $uploaded; + + die(); + } + protected function validate(UploadedFile $file) { // check if the file size submited by the client is over the max size in our config diff --git a/Uploader/Response/BlueimpResponse.php b/Uploader/Response/BlueimpResponse.php deleted file mode 100644 index e5fd1a3..0000000 --- a/Uploader/Response/BlueimpResponse.php +++ /dev/null @@ -1,43 +0,0 @@ -<?php - -namespace Oneup\UploaderBundle\Uploader\Response; - -use Oneup\UploaderBundle\Uploader\Response\AbstractResponse; - -class BlueimpResponse extends AbstractResponse -{ - /** - * This is an array containing elements of the following type - * array(url, thumbnail_url, type, size, delete_url, delete_type) - */ - protected $files; - - public function __construct() - { - $this->files = array(); - - parent::__construct(); - } - - public function assemble() - { - $data = $this->data; - $data['files'] = $this->files; - - return $data; - } - - public function addFile($file) - { - $this->files[] = $file; - - return $this; - } - - public function setFiles(array $files) - { - $this->files = $files; - - return $this; - } -} \ No newline at end of file diff --git a/Uploader/Response/EmptyResponse.php b/Uploader/Response/EmptyResponse.php new file mode 100644 index 0000000..3fa6f6c --- /dev/null +++ b/Uploader/Response/EmptyResponse.php @@ -0,0 +1,14 @@ +<?php + +namespace Oneup\UploaderBundle\Uploader\Response; + +use Oneup\UploaderBundle\Uploader\Response\AbstractResponse; + +class EmptyResponse extends AbstractResponse +{ + public function assemble() + { + return $this->data; + } + +} \ No newline at end of file
0
0223eea4a97a72fe27f6a157ca5c9306c7199149
1up-lab/OneupUploaderBundle
Update orphanage.md
commit 0223eea4a97a72fe27f6a157ca5c9306c7199149 Author: mitom <[email protected]> Date: Fri Oct 11 13:25:01 2013 +0200 Update orphanage.md diff --git a/Resources/doc/orphanage.md b/Resources/doc/orphanage.md index 59478cd..b4051a2 100644 --- a/Resources/doc/orphanage.md +++ b/Resources/doc/orphanage.md @@ -67,6 +67,12 @@ oneup_uploader: You can choose a custom directory to save the orphans temporarily while uploading by changing the parameter `directory`. +If you are using a gaufrette filesystem as the chunk storage, the ```directory``` specified above should be +relative to the filesystem's root directory. It will detect if you are using a gaufrette chunk storage +and default to ```orphanage```. + +> The orphanage and the chunk storage are forced to be on the same filesystem. + ## Clean up The `OrphanageManager` can be forced to clean up orphans by using the command provided by the OneupUploaderBundle. @@ -79,4 +85,4 @@ The `Orphanage` will save uploaded files in a directory like the following: %kernel.cache_dir%/uploader/orphanage/{session_id}/uploaded_file.ext -It is currently not possible to change the part after `%kernel.cache_dir%/uploader/orphanage` dynamically. This has some implications. If a user will upload files through your `gallery` mapping, and choose not to submit the form, but instead start over with a new form handled by the `gallery` mapping, the newly uploaded files are going to be moved in the same directory. Therefore you will get both the files uploaded the first time and the second time if you trigger the `uploadFiles` method. \ No newline at end of file +It is currently not possible to change the part after `%kernel.cache_dir%/uploader/orphanage` dynamically. This has some implications. If a user will upload files through your `gallery` mapping, and choose not to submit the form, but instead start over with a new form handled by the `gallery` mapping, the newly uploaded files are going to be moved in the same directory. Therefore you will get both the files uploaded the first time and the second time if you trigger the `uploadFiles` method.
0
d78d36afa2079e1e301334550e20c0d90ff2623d
1up-lab/OneupUploaderBundle
Update gaufrette_storage.md
commit d78d36afa2079e1e301334550e20c0d90ff2623d Author: Jim Schmid <[email protected]> Date: Tue Apr 9 09:46:49 2013 +0300 Update gaufrette_storage.md diff --git a/Resources/doc/gaufrette_storage.md b/Resources/doc/gaufrette_storage.md index 74ec3fe..14e1788 100644 --- a/Resources/doc/gaufrette_storage.md +++ b/Resources/doc/gaufrette_storage.md @@ -45,6 +45,8 @@ public function registerBundles() The following is a sample configuration for the KnpGaufretteBundle. It will create a filystem service called `gaufrette.gallery_filesystem` which can be used in the OneupUploaderBundle. For a complete list of features refer to the [official documentation](https://github.com/KnpLabs/KnpGaufretteBundle). ```yml +# app/config/config.yml + knp_gaufrette: adapters: gallery: @@ -55,8 +57,6 @@ knp_gaufrette: filesystems: gallery: adapter: gallery - - stream_wrapper: ~ ``` ## Configure your mappings @@ -64,6 +64,8 @@ knp_gaufrette: Activate Gaufrette by switching the `type` property to `gaufrette` and pass the Gaufrette filesystem configured in the previous step. ```yml +# app/config/config.yml + oneup_uploader: mappings: gallery:
0
bfc3e819184effe3e49a0c7b7cf7ccc3bb0ca313
1up-lab/OneupUploaderBundle
Merge pull request #63 from Paulmolin/release-1.0 Fix configuration for storage service creation
commit bfc3e819184effe3e49a0c7b7cf7ccc3bb0ca313 (from c9c64c94c6d96b4532b4a18c238205ebf6b058f4) Merge: c9c64c9 b17bee4 Author: Jim Schmid <[email protected]> Date: Tue Oct 15 02:39:46 2013 -0700 Merge pull request #63 from Paulmolin/release-1.0 Fix configuration for storage service creation diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index c017bdc..f6720a6 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -169,7 +169,7 @@ class OneupUploaderExtension extends Extension // if a service is given, return a reference to this service // this allows a user to overwrite the storage layer if needed if (!is_null($config['service'])) { - $storageService = new Reference($config['storage']['service']); + $storageService = new Reference($config['service']); } else { // no service was given, so we create one $storageName = sprintf('oneup_uploader.storage.%s', $key);
0
3c394b6c7267b25b32732e16433340940674bcda
1up-lab/OneupUploaderBundle
Cleaned up used namespaces on two of the controllers.
commit 3c394b6c7267b25b32732e16433340940674bcda Author: Jim Schmid <[email protected]> Date: Thu Apr 11 20:43:21 2013 +0200 Cleaned up used namespaces on two of the controllers. diff --git a/Controller/BlueimpController.php b/Controller/BlueimpController.php index e2c6026..311c4fa 100644 --- a/Controller/BlueimpController.php +++ b/Controller/BlueimpController.php @@ -2,17 +2,11 @@ namespace Oneup\UploaderBundle\Controller; -use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\HttpFoundation\File\Exception\UploadException; -use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; -use Oneup\UploaderBundle\UploadEvents; -use Oneup\UploaderBundle\Event\PostPersistEvent; -use Oneup\UploaderBundle\Event\PostUploadEvent; -use Oneup\UploaderBundle\Controller\AbstractController; -use Oneup\UploaderBundle\Uploader\Storage\StorageInterface; +use Oneup\UploaderBundle\Controller\AbstractChunkedController; use Oneup\UploaderBundle\Uploader\Response\EmptyResponse; class BlueimpController extends AbstractChunkedController diff --git a/Controller/FineUploaderController.php b/Controller/FineUploaderController.php index 7fcbace..37aa0b4 100644 --- a/Controller/FineUploaderController.php +++ b/Controller/FineUploaderController.php @@ -2,17 +2,11 @@ namespace Oneup\UploaderBundle\Controller; -use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\HttpFoundation\File\Exception\UploadException; -use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; -use Oneup\UploaderBundle\UploadEvents; -use Oneup\UploaderBundle\Event\PostPersistEvent; -use Oneup\UploaderBundle\Event\PostUploadEvent; use Oneup\UploaderBundle\Controller\AbstractChunkedController; -use Oneup\UploaderBundle\Uploader\Storage\StorageInterface; use Oneup\UploaderBundle\Uploader\Response\FineUploaderResponse; class FineUploaderController extends AbstractChunkedController
0
46ed8f73d1e8fd5f82695e09f476fb93ae15206a
1up-lab/OneupUploaderBundle
Added Template helpers Reference documentation.
commit 46ed8f73d1e8fd5f82695e09f476fb93ae15206a Author: Jim Schmid <[email protected]> Date: Sun Dec 15 10:05:03 2013 +0100 Added Template helpers Reference documentation. diff --git a/Resources/doc/index.md b/Resources/doc/index.md index 0fd9169..f384284 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -130,6 +130,7 @@ some more advanced features. * [General/Generic Events](events.md) * [Enable Session upload progress / upload cancelation](progress.md) * [Use Chunked Uploads behind Load Balancers](load_balancers.md) +* [Template helpers Reference](templating.md) * [Configuration Reference](configuration_reference.md) * [Testing this bundle](testing.md) diff --git a/Resources/doc/templating.md b/Resources/doc/templating.md new file mode 100644 index 0000000..a0b27c5 --- /dev/null +++ b/Resources/doc/templating.md @@ -0,0 +1,18 @@ +Template Helpers +================ + +The following template helpers are available. + +* `oneup_uploader_endpoint` Returns the endpoint route to which the uploader should send its files. +* `oneup_uploader_progress` Returns the route where you can ping the progress of a given file if configured. +* `oneup_uploader_cancel` Returns the route where you can cancel an upload if configured. +* `oneup_uploader_upload_key` Returns the php.ini variable `session.upload_progress.name`. You may need this for getting progress configured. +* `oneup_uploader_maxsize` Returns the configured max size value in bytes for a given mapping. + +Use these helpers in your templates like this: + +```twig +{{ oneup_uploader_endpoint('gallery') }} +``` + +> **Note**: `oneup_uploader_upload_key` does not need a mapping key. \ No newline at end of file
0
341c88053299b932efefbd1ae068b2cae9a267da
1up-lab/OneupUploaderBundle
Test against null to avoid object to boolean conversion.
commit 341c88053299b932efefbd1ae068b2cae9a267da Author: Jim Schmid <[email protected]> Date: Mon Oct 14 21:31:37 2013 +0200 Test against null to avoid object to boolean conversion. diff --git a/Controller/AbstractChunkedController.php b/Controller/AbstractChunkedController.php index 2e803bb..db4d784 100644 --- a/Controller/AbstractChunkedController.php +++ b/Controller/AbstractChunkedController.php @@ -60,7 +60,8 @@ abstract class AbstractChunkedController extends AbstractController if ($chunkManager->getLoadDistribution()) { $chunks = $chunkManager->getChunks($uuid); $assembled = $chunkManager->assembleChunks($chunks, true, $last); - if (!$chunk) { + + if (is_null($chunk)) { $this->dispatchChunkEvents($assembled, $response, $request, $last); } }
0
f19277d0cf7fe3ce1ce7b7582149288f90fa134d
1up-lab/OneupUploaderBundle
Added a knp_gaufrette configuration with local adapters to documentation.
commit f19277d0cf7fe3ce1ce7b7582149288f90fa134d Author: Jim Schmid <[email protected]> Date: Sun Apr 7 20:22:07 2013 +0200 Added a knp_gaufrette configuration with local adapters to documentation. diff --git a/Resources/doc/gaufrette_storage.md b/Resources/doc/gaufrette_storage.md index 9dc6b51..4205957 100644 --- a/Resources/doc/gaufrette_storage.md +++ b/Resources/doc/gaufrette_storage.md @@ -42,6 +42,21 @@ public function registerBundles() ## Configure your Filesystems +```yml +knp_gaufrette: + adapters: + gallery: + local: + directory: %kernel.root_dir%/../web/uploads + create: true + + filesystems: + gallery: + adapter: gallery + + stream_wrapper: ~ +``` + ## Configure your mappings ```yml
0
4e79231a74e40d2d3fe24bb78fa360e640138753
1up-lab/OneupUploaderBundle
Use composer v2 (#387)
commit 4e79231a74e40d2d3fe24bb78fa360e640138753 Author: David Greminger <[email protected]> Date: Mon Oct 26 18:29:27 2020 +0100 Use composer v2 (#387) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7605e04..47757f4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,11 +14,10 @@ jobs: runs-on: ubuntu-latest steps: - name: Setup PHP - uses: shivammathur/setup-php@v2 + uses: shivammathur/[email protected] with: php-version: 7.4 extensions: dom, fileinfo, filter, gd, hash, intl, json, mbstring, pcre, pdo, zlib - tools: prestissimo coverage: none - name: Checkout @@ -41,11 +40,10 @@ jobs: symfony: [4.4, 5.0] steps: - name: Setup PHP - uses: shivammathur/setup-php@v2 + uses: shivammathur/[email protected] with: php-version: ${{ matrix.php }} extensions: dom, fileinfo, filter, gd, hash, intl, json, mbstring, pcre, pdo_mysql, zlib - tools: prestissimo coverage: none - name: Checkout @@ -63,11 +61,10 @@ jobs: runs-on: ubuntu-latest steps: - name: Setup PHP - uses: shivammathur/setup-php@v2 + uses: shivammathur/[email protected] with: php-version: 7.2 extensions: dom, fileinfo, filter, gd, hash, intl, json, mbstring, pcre, pdo_mysql, zlib - tools: prestissimo coverage: none - name: Checkout
0
77ff8ab11fa0d8b3724be87529e9ce383bc5c730
1up-lab/OneupUploaderBundle
Removed unused prefix input variable.
commit 77ff8ab11fa0d8b3724be87529e9ce383bc5c730 Author: Jim Schmid <[email protected]> Date: Sun Apr 7 19:52:12 2013 +0200 Removed unused prefix input variable. diff --git a/Uploader/Naming/UniqidNamer.php b/Uploader/Naming/UniqidNamer.php index 1063205..af408d2 100644 --- a/Uploader/Naming/UniqidNamer.php +++ b/Uploader/Naming/UniqidNamer.php @@ -7,7 +7,7 @@ use Oneup\UploaderBundle\Uploader\Naming\NamerInterface; class UniqidNamer implements NamerInterface { - public function name(UploadedFile $file, $prefix = null) + public function name(UploadedFile $file) { return sprintf('%s.%s', uniqid(), $file->guessExtension()); }
0
0cd04fbd9a7b9649e9d537c8cb15ade0be0333f2
1up-lab/OneupUploaderBundle
Merge branch 'master' of github.com:1up-lab/OneupUploaderBundle
commit 0cd04fbd9a7b9649e9d537c8cb15ade0be0333f2 (from e39ec00ec362fec0e2df73d707b86b53ee85cc31) Merge: e39ec00 dac8568 Author: Jim Schmid <[email protected]> Date: Thu Jul 25 20:17:47 2013 +0200 Merge branch 'master' of github.com:1up-lab/OneupUploaderBundle diff --git a/README.md b/README.md index cfdfbdb..0df2f93 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,3 @@ -*** - -**Warning**: There is currently a pretty serious issue reported. Until further notice, -consider chunked uploads as *not-working*. It is highly recommended to switch from chunked -uploads to non-chunked uploads until this issue is fixed again. You can find more -information in ticket [#21](https://github.com/1up-lab/OneupUploaderBundle/issues/21). - -*** - - OneupUploaderBundle =================== commit 0cd04fbd9a7b9649e9d537c8cb15ade0be0333f2 (from dac856885ff3c980f82c7e3cd70e4cd755f39fe7) Merge: e39ec00 dac8568 Author: Jim Schmid <[email protected]> Date: Thu Jul 25 20:17:47 2013 +0200 Merge branch 'master' of github.com:1up-lab/OneupUploaderBundle diff --git a/Controller/AbstractChunkedController.php b/Controller/AbstractChunkedController.php index d7b0365..020d315 100644 --- a/Controller/AbstractChunkedController.php +++ b/Controller/AbstractChunkedController.php @@ -74,10 +74,7 @@ abstract class AbstractChunkedController extends AbstractController $path = $assembled->getPath(); // create a temporary uploaded file to meet the interface restrictions - $uploadedFile = new UploadedFile($assembled->getPathname(), $assembled->getBasename(), null, null, null, true); - - // validate this entity and upload on success - $this->validate($uploadedFile); + $uploadedFile = new UploadedFile($assembled->getPathname(), $assembled->getBasename(), null, $assembled->getSize(), null, true); $uploaded = $this->handleUpload($uploadedFile, $response, $request); $chunkManager->cleanup($path); diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index 8543d7d..6472e05 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -57,6 +57,7 @@ class Configuration implements ConfigurationInterface ->end() ->scalarNode('filesystem')->defaultNull()->end() ->scalarNode('directory')->defaultNull()->end() + ->scalarNode('sync_buffer_size')->defaultValue('100K')->end() ->end() ->end() ->arrayNode('allowed_extensions') diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index 4e9b72a..fa4cb90 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -84,6 +84,7 @@ class OneupUploaderExtension extends Extension $container ->register($storageName, sprintf('%%oneup_uploader.storage.%s.class%%', $mapping['storage']['type'])) ->addArgument(new Reference($mapping['storage']['filesystem'])) + ->addArgument($this->getValueInBytes($mapping['storage']['sync_buffer_size'])) ; } diff --git a/Resources/doc/configuration_reference.md b/Resources/doc/configuration_reference.md index 7273963..b75fee4 100644 --- a/Resources/doc/configuration_reference.md +++ b/Resources/doc/configuration_reference.md @@ -26,11 +26,12 @@ oneup_uploader: type: filesystem filesystem: ~ directory: ~ + sync_buffer_size: 100K allowed_extensions: [] disallowed_extensions: [] allowed_mimetypes: [] disallowed_mimetypes: [] - error_handler: oneup_uploader.error_handler.noop + error_handler: oneup_uploader.error_handler.noop # Set max_size to -1 for gracefully downgrade this number to the systems max upload size. max_size: 9223372036854775807 diff --git a/Resources/doc/gaufrette_storage.md b/Resources/doc/gaufrette_storage.md index 14e1788..6c93347 100644 --- a/Resources/doc/gaufrette_storage.md +++ b/Resources/doc/gaufrette_storage.md @@ -74,3 +74,17 @@ oneup_uploader: filesystem: gaufrette.gallery_filesystem ``` +You can specify the buffer size used for syncing files from your filesystem to the gaufrette storage by changing the property `sync_buffer_size`. + +```yml +# app/config/config.yml + +oneup_uploader: + mappings: + gallery: + storage: + type: gaufrette + filesystem: gaufrette.gallery_filesystem + sync_buffer_size: 1M +``` + diff --git a/Tests/Controller/AbstractChunkedUploadTest.php b/Tests/Controller/AbstractChunkedUploadTest.php index bbc4bc9..cd70c1e 100644 --- a/Tests/Controller/AbstractChunkedUploadTest.php +++ b/Tests/Controller/AbstractChunkedUploadTest.php @@ -6,6 +6,8 @@ use Symfony\Component\EventDispatcher\Event; use Oneup\UploaderBundle\Tests\Controller\AbstractUploadTest; use Oneup\UploaderBundle\Event\PostChunkUploadEvent; use Oneup\UploaderBundle\Event\PreUploadEvent; +use Oneup\UploaderBundle\Event\PostUploadEvent; +use Oneup\UploaderBundle\Event\ValidationEvent; use Oneup\UploaderBundle\UploadEvents; abstract class AbstractChunkedUploadTest extends AbstractUploadTest @@ -21,6 +23,7 @@ abstract class AbstractChunkedUploadTest extends AbstractUploadTest $me = $this; $endpoint = $this->helper->endpoint($this->getConfigKey()); $basename = ''; + $validationCount = 0; for ($i = 0; $i < $this->total; $i ++) { $file = $this->getNextFile($i); @@ -35,15 +38,23 @@ abstract class AbstractChunkedUploadTest extends AbstractUploadTest $dispatcher->addListener(UploadEvents::PRE_UPLOAD, function(PreUploadEvent $event) use (&$me, $basename) { $file = $event->getFile(); + $me->assertNotNull($file->getClientSize()); + $me->assertGreaterThan(0, $file->getClientSize()); $me->assertEquals($file->getBasename(), $basename); }); + $dispatcher->addListener(UploadEvents::VALIDATION, function(ValidationEvent $event) use (&$validationCount) { + ++ $validationCount; + }); + $client->request('POST', $endpoint, $this->getNextRequestParameters($i), array($file)); $response = $client->getResponse(); $this->assertTrue($response->isSuccessful()); $this->assertEquals($response->headers->get('Content-Type'), 'application/json'); } + + $this->assertEquals(1, $validationCount); foreach ($this->getUploadedFiles() as $file) { $this->assertTrue($file->isFile()); diff --git a/Tests/Uploader/Storage/GaufretteStorageTest.php b/Tests/Uploader/Storage/GaufretteStorageTest.php index d2656ee..f9ecfe6 100644 --- a/Tests/Uploader/Storage/GaufretteStorageTest.php +++ b/Tests/Uploader/Storage/GaufretteStorageTest.php @@ -28,7 +28,7 @@ class GaufretteStorageTest extends \PHPUnit_Framework_TestCase $adapter = new Adapter($this->directory, true); $filesystem = new GaufretteFilesystem($adapter); - $this->storage = new GaufretteStorage($filesystem); + $this->storage = new GaufretteStorage($filesystem, 100000); } public function testUpload() diff --git a/Uploader/Chunk/ChunkManagerInterface.php b/Uploader/Chunk/ChunkManagerInterface.php index 3fad75a..1ba2c15 100644 --- a/Uploader/Chunk/ChunkManagerInterface.php +++ b/Uploader/Chunk/ChunkManagerInterface.php @@ -8,7 +8,7 @@ interface ChunkManagerInterface { public function clear(); public function addChunk($uuid, $index, UploadedFile $chunk, $original); - public function assembleChunks(\IteratorAggregate $chunks); + public function assembleChunks(\IteratorAggregate $chunks, $removeChunk = true, $renameChunk = false); public function cleanup($path); public function getChunks($uuid); } diff --git a/Uploader/Storage/GaufretteStorage.php b/Uploader/Storage/GaufretteStorage.php index ea8a6b3..2fbd349 100644 --- a/Uploader/Storage/GaufretteStorage.php +++ b/Uploader/Storage/GaufretteStorage.php @@ -13,10 +13,12 @@ use Oneup\UploaderBundle\Uploader\Storage\StorageInterface; class GaufretteStorage implements StorageInterface { protected $filesystem; + protected $bufferSize; - public function __construct(Filesystem $filesystem) + public function __construct(Filesystem $filesystem, $bufferSize) { $this->filesystem = $filesystem; + $this->bufferSize = $bufferSize; } public function upload(File $file, $name, $path = null) @@ -40,7 +42,7 @@ class GaufretteStorage implements StorageInterface $dst->open(new StreamMode('wb+')); while (!$src->eof()) { - $data = $src->read(100000); + $data = $src->read($this->bufferSize); $written = $dst->write($data); }
0
d1076f0a0a365229c6c5091afd1b6be744fbccef
1up-lab/OneupUploaderBundle
Self update composer before testing
commit d1076f0a0a365229c6c5091afd1b6be744fbccef Author: Jim Schmid <[email protected]> Date: Fri Jul 18 18:17:39 2014 +0200 Self update composer before testing diff --git a/.travis.yml b/.travis.yml index 1d74818..5a3affa 100644 --- a/.travis.yml +++ b/.travis.yml @@ -23,5 +23,6 @@ matrix: env: SYMFONY_VERSION=dev-master before_script: + - composer selfupdate - composer require symfony/framework-bundle:${SYMFONY_VERSION} --prefer-source - composer install --dev --prefer-source
0
b33a0b85389f328c6b392d21f638254f1d640eb5
1up-lab/OneupUploaderBundle
First and incomplete version of the MooUpload implementation. (defunct)
commit b33a0b85389f328c6b392d21f638254f1d640eb5 Author: Jim Schmid <[email protected]> Date: Fri Apr 12 11:17:46 2013 +0200 First and incomplete version of the MooUpload implementation. (defunct) diff --git a/Controller/MooUploadController.php b/Controller/MooUploadController.php new file mode 100644 index 0000000..fcd2435 --- /dev/null +++ b/Controller/MooUploadController.php @@ -0,0 +1,122 @@ +<?php + +namespace Oneup\UploaderBundle\Controller; + +use Symfony\Component\HttpFoundation\File\UploadedFile; +use Symfony\Component\HttpFoundation\File\Exception\UploadException; +use Symfony\Component\HttpFoundation\JsonResponse; +use Symfony\Component\HttpFoundation\Request; + +use Oneup\UploaderBundle\Controller\AbstractChunkedController; +use Oneup\UploaderBundle\Uploader\Response\MooUploadResponse; + +class MooUploadController extends AbstractChunkedController +{ + protected $response; + + public function upload() + { + $request = $this->container->get('request'); + $dispatcher = $this->container->get('event_dispatcher'); + $translator = $this->container->get('translator'); + + $response = new MooUploadResponse(); + $files = $request->files; + $headers = $request->headers; + + // we have to get access to this object in another method + $this->response = $response; + + // create temporary file in systems temp dir + $tempFile = tempnam(sys_get_temp_dir(), 'uploader'); + $contents = file_get_contents('php://input'); + + // put data from php://input to temp file + file_put_contents($tempFile, $contents); + + $uploadFileName = sprintf('%s_%s', $headers->get('x-file-id'), $headers->get('x-file-name')); + + // create an uploaded file to upload + $file = new UploadedFile($tempFile, $uploadFileName, null, null, null, true); + + // check if uploaded by chunks + $chunked = $headers->get('content-length') < $headers->get('x-file-size'); + + try + { + $uploaded = $chunked ? $this->handleChunkedUpload($file) : $this->handleUpload($file); + + // fill response object + $response = $this->response; + + $response->setId($headers->get('x-file-id')); + $response->setSize($headers->get('x-file-size')); + $response->setName($headers->get('x-file-name')); + $response->setUploadedName($uploadFileName); + + // dispatch POST_PERSIST AND POST_UPLOAD events + $this->dispatchEvents($uploaded, $response, $request); + } + catch(UploadException $e) + { + $response = $this->response; + + $response->setFinish(true); + $response->setError(-1); + + // return nothing + return new JsonResponse($response->assemble()); + } + + return new JsonResponse($response->assemble()); + } + + protected function parseChunkedRequest(Request $request) + { + $chunkManager = $this->container->get('oneup_uploader.chunk_manager'); + $headers = $request->headers; + $parameters = array_keys($request->query->all()); + + $uuid = $headers->get('x-file-id'); + $index = $this->createIndex($parameters[0]); + $orig = $headers->get('x-file-name'); + $size = 0; + + try + { + // loop through every file that has been uploaded before + foreach($chunkManager->getChunks($uuid) as $file) + { + $size += $file->getSize(); + } + } + catch(\InvalidArgumentException $e) + { + // do nothing: this exception will be thrown + // if the directory does not yet exist. this + // means we don't have a chunk and the actual + // size is 0 + } + + $last = $headers->get('x-file-size') == ($size + $headers->get('content-length')); + + // store also to response object + $this->response->setFinish($last); + + return array($last, $uuid, $index, $orig); + } + + protected function createIndex($id) + { + $ints = ''; + + // loop through every char and convert it to an integer + // we need this for sorting + foreach(str_split($id) as $char) + { + $ints .= ord($char); + } + + return $ints; + } +} \ No newline at end of file diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index b97806e..b00f847 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -35,7 +35,7 @@ class Configuration implements ConfigurationInterface ->prototype('array') ->children() ->enumNode('frontend') - ->values(array('fineuploader', 'blueimp', 'uploadify', 'yui3', 'fancyupload')) + ->values(array('fineuploader', 'blueimp', 'uploadify', 'yui3', 'fancyupload', 'mooupload')) ->defaultValue('fineuploader') ->end() ->arrayNode('storage') diff --git a/Resources/config/uploader.xml b/Resources/config/uploader.xml index 1a1108d..8b1cc48 100644 --- a/Resources/config/uploader.xml +++ b/Resources/config/uploader.xml @@ -16,6 +16,7 @@ <parameter key="oneup_uploader.controller.uploadify.class">Oneup\UploaderBundle\Controller\UploadifyController</parameter> <parameter key="oneup_uploader.controller.yui3.class">Oneup\UploaderBundle\Controller\YUI3Controller</parameter> <parameter key="oneup_uploader.controller.fancyupload.class">Oneup\UploaderBundle\Controller\FancyUploadController</parameter> + <parameter key="oneup_uploader.controller.mooupload.class">Oneup\UploaderBundle\Controller\MooUploadController</parameter> </parameters> <services> diff --git a/Uploader/Response/MooUploadResponse.php b/Uploader/Response/MooUploadResponse.php new file mode 100644 index 0000000..36e8572 --- /dev/null +++ b/Uploader/Response/MooUploadResponse.php @@ -0,0 +1,109 @@ +<?php + +namespace Oneup\UploaderBundle\Uploader\Response; + +use Oneup\UploaderBundle\Uploader\Response\AbstractResponse; + +class MooUploadResponse extends AbstractResponse +{ + protected $id; + protected $name; + protected $size; + protected $error; + protected $finish; + protected $uploadedName; + + public function __construct() + { + $this->finish = true; + $this->error = 0; + + parent::__construct(); + } + + public function assemble() + { + $data = $this->data; + + $data['id'] = $this->id; + $data['name'] = $this->name; + $data['size'] = $this->size; + $data['error'] = $this->error; + $data['finish'] = $this->finish; + $data['upload_name'] = $this->uploadedName; + + return $data; + } + + public function setId($id) + { + $this->id = $id; + + return $this; + } + + public function getId() + { + return $this->id; + } + + public function setName($name) + { + $this->name = $name; + + return $this; + } + + public function getName() + { + return $this->id; + } + + public function setSize($size) + { + $this->size = $size; + + return $this; + } + + public function getSize() + { + return $this->size; + } + + public function setError($error) + { + $this->error = $error; + + return $this; + } + + public function getError() + { + return $this->error; + } + + public function setFinish($finish) + { + $this->finish = $finish; + + return $this; + } + + public function getFinish() + { + return $this->finish; + } + + public function setUploadedName($name) + { + $this->uploadedName = $name; + + return $this; + } + + public function getUploadedName() + { + return $this->uploadedName; + } +} \ No newline at end of file
0
530858cbefb4bb3ea1b147b032514f779df7c814
1up-lab/OneupUploaderBundle
Fix .gitignore
commit 530858cbefb4bb3ea1b147b032514f779df7c814 Author: David Greminger <[email protected]> Date: Fri Oct 23 11:36:41 2020 +0200 Fix .gitignore diff --git a/.gitignore b/.gitignore index 0204479..68a1a75 100644 --- a/.gitignore +++ b/.gitignore @@ -1,11 +1,8 @@ +.idea +.phpunit.result.cache composer.lock -phpunit.xml vendor -log -var tests/App/cache tests/App/logs +tests/App/var tests/var - -.idea -.phpunit.result.cache
0
4b74fb3d3416720b758a4474e99a166c8a024a15
1up-lab/OneupUploaderBundle
Removed config var 'action'
commit 4b74fb3d3416720b758a4474e99a166c8a024a15 Author: Jim Schmid <[email protected]> Date: Wed Mar 13 10:35:07 2013 +0100 Removed config var 'action' diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index 171d66e..829ae62 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -37,7 +37,6 @@ class Configuration implements ConfigurationInterface ->scalarNode('storage')->isRequired()->end() ->scalarNode('directory_prefix')->end() ->booleanNode('use_orphanage')->defaultFalse()->end() - ->scalarNode('action')->defaultNull()->end() ->scalarNode('namer')->defaultValue('oneup_uploader.namer.uniqid')->end() ->end() ->end()
0
d02c6d19f0ad13d58c604589134612ad3ddc3b96
1up-lab/OneupUploaderBundle
added services to the wrong section
commit d02c6d19f0ad13d58c604589134612ad3ddc3b96 Author: Martin Aarhof <[email protected]> Date: Thu Dec 17 18:57:12 2015 +0100 added services to the wrong section diff --git a/Resources/doc/custom_namer.md b/Resources/doc/custom_namer.md index ffc7a03..c83002d 100644 --- a/Resources/doc/custom_namer.md +++ b/Resources/doc/custom_namer.md @@ -35,18 +35,18 @@ Next, register your created namer as a service in your `services.xml` ``` ```yml -acme_demo.custom_namer: - class: Acme\DemoBundle\CatNamer +services: + acme_demo.custom_namer: + class: Acme\DemoBundle\CatNamer ``` Now you can use your custom service by adding it to your configuration: ```yml -services: - oneup_uploader: - mappings: - gallery: - namer: acme_demo.custom_namer +oneup_uploader: + mappings: + gallery: + namer: acme_demo.custom_namer ``` Every file uploaded through the `Controller` of this mapping will be named with your custom namer.
0
fe51b5f18779f172b553105bf19b63ca916bdf15
1up-lab/OneupUploaderBundle
Changed name of ControllerTest as I'm going to implement the chunked upload test afterwards.
commit fe51b5f18779f172b553105bf19b63ca916bdf15 Author: Jim Schmid <[email protected]> Date: Sat Apr 6 17:01:16 2013 +0200 Changed name of ControllerTest as I'm going to implement the chunked upload test afterwards. diff --git a/Tests/Controller/ControllerTest.php b/Tests/Controller/ControllerUploadTest.php similarity index 98% rename from Tests/Controller/ControllerTest.php rename to Tests/Controller/ControllerUploadTest.php index bf433f9..7bd7fc8 100644 --- a/Tests/Controller/ControllerTest.php +++ b/Tests/Controller/ControllerUploadTest.php @@ -10,7 +10,7 @@ use Oneup\UploaderBundle\Uploader\Naming\UniqidNamer; use Oneup\UploaderBundle\Uploader\Storage\FilesystemStorage; use Oneup\UploaderBundle\Controller\UploaderController; -class ControllerTest extends \PHPUnit_Framework_TestCase +class ControllerUploadTest extends \PHPUnit_Framework_TestCase { protected $tempFile;
0
bdef0e2c77ffc20516b012956b2dfeed68b9bbf4
1up-lab/OneupUploaderBundle
Remove empty directories when cleaning up orphanage (see #153)
commit bdef0e2c77ffc20516b012956b2dfeed68b9bbf4 Author: David Greminger <[email protected]> Date: Fri Sep 15 16:40:13 2017 +0200 Remove empty directories when cleaning up orphanage (see #153) diff --git a/Uploader/Orphanage/OrphanageManager.php b/Uploader/Orphanage/OrphanageManager.php index 9442712..4733b76 100644 --- a/Uploader/Orphanage/OrphanageManager.php +++ b/Uploader/Orphanage/OrphanageManager.php @@ -52,5 +52,21 @@ class OrphanageManager foreach ($finder as $file) { $system->remove($file); } + + // Now that the files are cleaned, we check if we need to remove some directories as well + // We use a new instance of the Finder as it as a state + $finder = new Finder(); + $finder->in($this->config['directory'])->directories(); + + $dirArray = iterator_to_array($finder, false); + $size = sizeof($dirArray); + + // We crawl the array backward as the Finder returns the parent first + for ($i = $size-1; $i >= 0; $i--) { + $dir = $dirArray[$i]; + if (!(new \FilesystemIterator($dir))->valid()) { + $system->remove($dir); + } + } } }
0
3a44a4ddff6ce854409c91afe331711935538a0b
1up-lab/OneupUploaderBundle
Trying to fix validation.xml config.
commit 3a44a4ddff6ce854409c91afe331711935538a0b Author: Jim Schmid <[email protected]> Date: Tue Apr 23 14:53:59 2013 +0200 Trying to fix validation.xml config. diff --git a/Resources/config/validation.xml b/Resources/config/validation.xml index 3daeb90..022dfbe 100644 --- a/Resources/config/validation.xml +++ b/Resources/config/validation.xml @@ -1,32 +1,20 @@ -<?xml version="1.0" encoding="UTF-8" ?> - +<?xml version="1.0" encoding="utf-8" ?> <container xmlns="http://symfony.com/schema/dic/services" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"> + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"> <services> - - <service - id="oneup_uploader.validation_listener.max_size" - class="Oneup\UploaderBundle\EventListener\MaxSizeValidationListener" - > + <service id="oneup_uploader.validation_listener.max_size" class="Oneup\UploaderBundle\EventListener\MaxSizeValidationListener"> <tag name="kernel.event_listener" event="oneup_uploader.validation" method="onValidate" /> </service> - <service - id="oneup_uploader.validation_listener.allowed_extension" - class="Oneup\UploaderBundle\EventListener\AllowedExtensionValidationListener" - > + <service id="oneup_uploader.validation_listener.allowed_extension" class="Oneup\UploaderBundle\EventListener\AllowedExtensionValidationListener" > <tag name="kernel.event_listener" event="oneup_uploader.validation" method="onValidate" /> </service> - <service - id="oneup_uploader.validation_listener.disallowed_extension" - class="Oneup\UploaderBundle\EventListener\DisallowedExtensionValidationListener" - > + <service id="oneup_uploader.validation_listener.disallowed_extension" class="Oneup\UploaderBundle\EventListener\DisallowedExtensionValidationListener"> <tag name="kernel.event_listener" event="oneup_uploader.validation" method="onValidate" /> </service> - </services> -</container> \ No newline at end of file +</container>
0
ea7994356b906846ac24c5dc2e90d9622f4d3949
1up-lab/OneupUploaderBundle
Start of validation tests (Blueimp/Uploadify included)
commit ea7994356b906846ac24c5dc2e90d9622f4d3949 Author: Jim Schmid <[email protected]> Date: Sat May 18 16:46:04 2013 +0200 Start of validation tests (Blueimp/Uploadify included) diff --git a/Tests/App/config/config.yml b/Tests/App/config/config.yml index d5265b7..a286251 100644 --- a/Tests/App/config/config.yml +++ b/Tests/App/config/config.yml @@ -48,8 +48,26 @@ oneup_uploader: frontend: uploadify storage: directory: %kernel.root_dir%/cache/%kernel.environment%/upload + + uploadify_validation: + frontend: uploadify + storage: + directory: %kernel.root_dir%/cache/%kernel.environment%/upload + allowed_extensions: [ "ok" ] + disallowed_extensions: [ "fail" ] + allowed_mimetypes: [ "image/jpg", "text/plain" ] + disallowed_mimetypes: [ "image/gif" ] blueimp: frontend: blueimp storage: - directory: %kernel.root_dir%/cache/%kernel.environment%/upload \ No newline at end of file + directory: %kernel.root_dir%/cache/%kernel.environment%/upload + + blueimp_validation: + frontend: blueimp + storage: + directory: %kernel.root_dir%/cache/%kernel.environment%/upload + allowed_extensions: [ "ok" ] + disallowed_extensions: [ "fail" ] + allowed_mimetypes: [ "image/jpg", "text/plain" ] + disallowed_mimetypes: [ "image/gif" ] \ No newline at end of file diff --git a/Tests/Controller/AbstractChunkedControllerTest.php b/Tests/Controller/AbstractChunkedUploadTest.php similarity index 87% rename from Tests/Controller/AbstractChunkedControllerTest.php rename to Tests/Controller/AbstractChunkedUploadTest.php index 61ea9c8..a5dfc2e 100644 --- a/Tests/Controller/AbstractChunkedControllerTest.php +++ b/Tests/Controller/AbstractChunkedUploadTest.php @@ -2,9 +2,9 @@ namespace Oneup\UploaderBundle\Tests\Controller; -use Oneup\UploaderBundle\Tests\Controller\AbstractControllerTest; +use Oneup\UploaderBundle\Tests\Controller\AbstractUploadTest; -abstract class AbstractChunkedControllerTest extends AbstractControllerTest +abstract class AbstractChunkedUploadTest extends AbstractUploadTest { protected $total = 6; diff --git a/Tests/Controller/AbstractControllerTest.php b/Tests/Controller/AbstractControllerTest.php index 14c966f..9ad0e1d 100644 --- a/Tests/Controller/AbstractControllerTest.php +++ b/Tests/Controller/AbstractControllerTest.php @@ -7,9 +7,9 @@ use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; abstract class AbstractControllerTest extends WebTestCase { + protected $createdFiles; protected $client; protected $container; - protected $createdFiles; public function setUp() { @@ -22,28 +22,6 @@ abstract class AbstractControllerTest extends WebTestCase } abstract protected function getConfigKey(); - abstract protected function getRequestParameters(); - abstract protected function getRequestFile(); - - public function testSingleUpload() - { - // assemble a request - $client = $this->client; - $endpoint = $this->helper->endpoint($this->getConfigKey()); - - $client->request('POST', $endpoint, $this->getRequestParameters(), array($this->getRequestFile())); - $response = $client->getResponse(); - - $this->assertTrue($response->isSuccessful()); - $this->assertEquals($response->headers->get('Content-Type'), 'application/json'); - $this->assertCount(1, $this->getUploadedFiles()); - - foreach($this->getUploadedFiles() as $file) { - $this->assertTrue($file->isFile()); - $this->assertTrue($file->isReadable()); - $this->assertEquals(128, $file->getSize()); - } - } public function testRoute() { @@ -91,7 +69,7 @@ abstract class AbstractControllerTest extends WebTestCase $this->assertTrue($response->isSuccessful()); $this->assertEquals($response->headers->get('Content-Type'), 'application/json'); } - + protected function createTempFile($size = 128) { $file = tempnam(sys_get_temp_dir(), 'uploader_'); @@ -125,5 +103,8 @@ abstract class AbstractControllerTest extends WebTestCase foreach($this->getUploadedFiles() as $file) { @unlink($file); } + + unset($this->client); + unset($this->controller); } } diff --git a/Tests/Controller/AbstractUploadTest.php b/Tests/Controller/AbstractUploadTest.php new file mode 100644 index 0000000..8603bd2 --- /dev/null +++ b/Tests/Controller/AbstractUploadTest.php @@ -0,0 +1,38 @@ +<?php + +namespace Oneup\UploaderBundle\Tests\Controller; + +use Oneup\UploaderBundle\Tests\Controller\AbstractControllerTest; + +abstract class AbstractUploadTest extends AbstractControllerTest +{ + abstract protected function getRequestParameters(); + abstract protected function getRequestFile(); + + public function setUp() + { + parent::setUp(); + + $this->createdFiles = array(); + } + + public function testSingleUpload() + { + // assemble a request + $client = $this->client; + $endpoint = $this->helper->endpoint($this->getConfigKey()); + + $client->request('POST', $endpoint, $this->getRequestParameters(), array($this->getRequestFile())); + $response = $client->getResponse(); + + $this->assertTrue($response->isSuccessful()); + $this->assertEquals($response->headers->get('Content-Type'), 'application/json'); + $this->assertCount(1, $this->getUploadedFiles()); + + foreach($this->getUploadedFiles() as $file) { + $this->assertTrue($file->isFile()); + $this->assertTrue($file->isReadable()); + $this->assertEquals(128, $file->getSize()); + } + } +} diff --git a/Tests/Controller/AbstractValidationTest.php b/Tests/Controller/AbstractValidationTest.php new file mode 100644 index 0000000..7f00774 --- /dev/null +++ b/Tests/Controller/AbstractValidationTest.php @@ -0,0 +1,81 @@ +<?php + +namespace Oneup\UploaderBundle\Tests\Controller; + +abstract class AbstractValidationTest extends AbstractControllerTest +{ + abstract protected function getFileWithCorrectExtension(); + abstract protected function getFileWithIncorrectExtension(); + abstract protected function getFileWithCorrectMimeType(); + abstract protected function getFileWithIncorrectMimeType(); + + public function testAgainstCorrectExtension() + { + // assemble a request + $client = $this->client; + $endpoint = $this->helper->endpoint($this->getConfigKey()); + + $client->request('POST', $endpoint, $this->getRequestParameters(), array($this->getFileWithCorrectExtension())); + $response = $client->getResponse(); + + $this->assertTrue($response->isSuccessful()); + $this->assertEquals($response->headers->get('Content-Type'), 'application/json'); + $this->assertCount(1, $this->getUploadedFiles()); + + foreach($this->getUploadedFiles() as $file) { + $this->assertTrue($file->isFile()); + $this->assertTrue($file->isReadable()); + $this->assertEquals(128, $file->getSize()); + } + } + + public function testAgainstIncorrectExtension() + { + // assemble a request + $client = $this->client; + $endpoint = $this->helper->endpoint($this->getConfigKey()); + + $client->request('POST', $endpoint, $this->getRequestParameters(), array($this->getFileWithIncorrectExtension())); + $response = $client->getResponse(); + + //$this->assertTrue($response->isNotSuccessful()); + $this->assertEquals($response->headers->get('Content-Type'), 'application/json'); + $this->assertCount(0, $this->getUploadedFiles()); + } + + public function testAgainstCorrectMimeType() + { + // assemble a request + $client = $this->client; + $endpoint = $this->helper->endpoint($this->getConfigKey()); + + $client->request('POST', $endpoint, $this->getRequestParameters(), array($this->getFileWithCorrectMimeType())); + $response = $client->getResponse(); + + $this->assertTrue($response->isSuccessful()); + $this->assertEquals($response->headers->get('Content-Type'), 'application/json'); + $this->assertCount(1, $this->getUploadedFiles()); + + foreach($this->getUploadedFiles() as $file) { + $this->assertTrue($file->isFile()); + $this->assertTrue($file->isReadable()); + $this->assertEquals(128, $file->getSize()); + } + } + + public function testAgainstIncorrectMimeType() + { + $this->markTestSkipped('Mock mime type getter.'); + + // assemble a request + $client = $this->client; + $endpoint = $this->helper->endpoint($this->getConfigKey()); + + $client->request('POST', $endpoint, $this->getRequestParameters(), array($this->getFileWithIncorrectMimeType())); + $response = $client->getResponse(); + + //$this->assertTrue($response->isNotSuccessful()); + $this->assertEquals($response->headers->get('Content-Type'), 'application/json'); + $this->assertCount(0, $this->getUploadedFiles()); + } +} diff --git a/Tests/Controller/BlueimpTest.php b/Tests/Controller/BlueimpTest.php index 51c9918..7814f66 100644 --- a/Tests/Controller/BlueimpTest.php +++ b/Tests/Controller/BlueimpTest.php @@ -3,9 +3,9 @@ namespace Oneup\UploaderBundle\Tests\Controller; use Symfony\Component\HttpFoundation\File\UploadedFile; -use Oneup\UploaderBundle\Tests\Controller\AbstractControllerTest; +use Oneup\UploaderBundle\Tests\Controller\AbstractUploadTest; -class BlueimpTest extends AbstractControllerTest +class BlueimpTest extends AbstractUploadTest { protected function getConfigKey() { diff --git a/Tests/Controller/BlueimpValidationTest.php b/Tests/Controller/BlueimpValidationTest.php new file mode 100644 index 0000000..8484951 --- /dev/null +++ b/Tests/Controller/BlueimpValidationTest.php @@ -0,0 +1,59 @@ +<?php + +namespace Oneup\UploaderBundle\Tests\Controller; + +use Symfony\Component\HttpFoundation\File\UploadedFile; +use Oneup\UploaderBundle\Tests\Controller\AbstractValidationTest; + +class BlueimpValidationTest extends AbstractValidationTest +{ + protected function getConfigKey() + { + return 'blueimp_validation'; + } + + protected function getRequestParameters() + { + return array(); + } + + protected function getFileWithCorrectExtension() + { + return array(new UploadedFile( + $this->createTempFile(128), + 'cat.ok', + 'text/plain', + 128 + )); + } + + protected function getFileWithIncorrectExtension() + { + return array(new UploadedFile( + $this->createTempFile(128), + 'cat.fail', + 'text/plain', + 128 + )); + } + + protected function getFileWithCorrectMimeType() + { + return array(new UploadedFile( + $this->createTempFile(128), + 'cat.ok', + 'image/jpg', + 128 + )); + } + + protected function getFileWithIncorrectMimeType() + { + return array(new UploadedFile( + $this->createTempFile(128), + 'cat.ok', + 'image/gif', + 128 + )); + } +} diff --git a/Tests/Controller/FancyUploadTest.php b/Tests/Controller/FancyUploadTest.php index e3069c5..7a014dd 100644 --- a/Tests/Controller/FancyUploadTest.php +++ b/Tests/Controller/FancyUploadTest.php @@ -3,9 +3,9 @@ namespace Oneup\UploaderBundle\Tests\Controller; use Symfony\Component\HttpFoundation\File\UploadedFile; -use Oneup\UploaderBundle\Tests\Controller\AbstractControllerTest; +use Oneup\UploaderBundle\Tests\Controller\AbstractUploadTest; -class FancyUploadTest extends AbstractControllerTest +class FancyUploadTest extends AbstractUploadTest { protected function getConfigKey() { diff --git a/Tests/Controller/FineUploaderTest.php b/Tests/Controller/FineUploaderTest.php index d2737ef..8bce50c 100644 --- a/Tests/Controller/FineUploaderTest.php +++ b/Tests/Controller/FineUploaderTest.php @@ -3,9 +3,9 @@ namespace Oneup\UploaderBundle\Tests\Controller; use Symfony\Component\HttpFoundation\File\UploadedFile; -use Oneup\UploaderBundle\Tests\Controller\AbstractControllerTest; +use Oneup\UploaderBundle\Tests\Controller\AbstractChunkedUploadTest; -class FineUploaderTest extends AbstractChunkedControllerTest +class FineUploaderTest extends AbstractChunkedUploadTest { protected function getConfigKey() { diff --git a/Tests/Controller/PluploadTest.php b/Tests/Controller/PluploadTest.php index 1cb80a8..d1ab541 100644 --- a/Tests/Controller/PluploadTest.php +++ b/Tests/Controller/PluploadTest.php @@ -3,9 +3,9 @@ namespace Oneup\UploaderBundle\Tests\Controller; use Symfony\Component\HttpFoundation\File\UploadedFile; -use Oneup\UploaderBundle\Tests\Controller\AbstractChunkedControllerTest; +use Oneup\UploaderBundle\Tests\Controller\AbstractChunkedUploadTest; -class PluploadTest extends AbstractChunkedControllerTest +class PluploadTest extends AbstractChunkedUploadTest { protected function getConfigKey() { diff --git a/Tests/Controller/UploadifyTest.php b/Tests/Controller/UploadifyTest.php index 8876760..32c4576 100644 --- a/Tests/Controller/UploadifyTest.php +++ b/Tests/Controller/UploadifyTest.php @@ -3,9 +3,9 @@ namespace Oneup\UploaderBundle\Tests\Controller; use Symfony\Component\HttpFoundation\File\UploadedFile; -use Oneup\UploaderBundle\Tests\Controller\AbstractControllerTest; +use Oneup\UploaderBundle\Tests\Controller\AbstractUploadTest; -class UploadifyTest extends AbstractControllerTest +class UploadifyTest extends AbstractUploadTest { protected function getConfigKey() { diff --git a/Tests/Controller/UploadifyValidationTest.php b/Tests/Controller/UploadifyValidationTest.php new file mode 100644 index 0000000..5b29e39 --- /dev/null +++ b/Tests/Controller/UploadifyValidationTest.php @@ -0,0 +1,60 @@ +<?php + +namespace Oneup\UploaderBundle\Tests\Controller; + +use Symfony\Component\HttpFoundation\File\UploadedFile; +use Oneup\UploaderBundle\Tests\Controller\AbstractValidationTest; + +class UploadifyValidationTest extends AbstractValidationTest +{ + + protected function getConfigKey() + { + return 'uploadify_validation'; + } + + protected function getRequestParameters() + { + return array(); + } + + protected function getFileWithCorrectExtension() + { + return new UploadedFile( + $this->createTempFile(128), + 'cat.ok', + 'text/plain', + 128 + ); + } + + protected function getFileWithIncorrectExtension() + { + return new UploadedFile( + $this->createTempFile(128), + 'cat.fail', + 'text/plain', + 128 + ); + } + + protected function getFileWithCorrectMimeType() + { + return new UploadedFile( + $this->createTempFile(128), + 'cat.ok', + 'image/jpg', + 128 + ); + } + + protected function getFileWithIncorrectMimeType() + { + return new UploadedFile( + $this->createTempFile(128), + 'cat.ok', + 'image/gif', + 128 + ); + } +} diff --git a/Tests/Controller/YUI3Test.php b/Tests/Controller/YUI3Test.php index 521d890..00b9ebf 100644 --- a/Tests/Controller/YUI3Test.php +++ b/Tests/Controller/YUI3Test.php @@ -3,9 +3,9 @@ namespace Oneup\UploaderBundle\Tests\Controller; use Symfony\Component\HttpFoundation\File\UploadedFile; -use Oneup\UploaderBundle\Tests\Controller\AbstractControllerTest; +use Oneup\UploaderBundle\Tests\Controller\AbstractUploadTest; -class YUI3Test extends AbstractControllerTest +class YUI3Test extends AbstractUploadTest { protected function getConfigKey() {
0
579bad5541b97463bfc31275a0779de9a6f850f9
1up-lab/OneupUploaderBundle
CS fixes.
commit 579bad5541b97463bfc31275a0779de9a6f850f9 Author: Jim Schmid <[email protected]> Date: Sun Apr 28 10:50:48 2013 +0200 CS fixes. diff --git a/Uploader/Response/AbstractResponse.php b/Uploader/Response/AbstractResponse.php index 1e97d50..c6b9145 100644 --- a/Uploader/Response/AbstractResponse.php +++ b/Uploader/Response/AbstractResponse.php @@ -19,10 +19,12 @@ abstract class AbstractResponse implements ResponseInterface { is_null($offset) ? $this->data[] = $value : $this->data[$offset] = $value; } + public function offsetExists($offset) { return isset($this->data[$offset]); } + public function offsetUnset($offset) { unset($this->data[$offset]);
0
e5b84278f1a1eb24f937545bd7758147aa24f739
1up-lab/OneupUploaderBundle
doc typo + yml hello ! : $tokenStorage typo => $this->tokenStorage + yml security conf
commit e5b84278f1a1eb24f937545bd7758147aa24f739 Author: MEDIA.figaro <[email protected]> Date: Mon Jun 27 18:34:07 2016 +0200 doc typo + yml hello ! : $tokenStorage typo => $this->tokenStorage + yml security conf diff --git a/Resources/doc/custom_namer.md b/Resources/doc/custom_namer.md index 257451d..fea6ee0 100644 --- a/Resources/doc/custom_namer.md +++ b/Resources/doc/custom_namer.md @@ -65,6 +65,13 @@ You need to inject the `security.token_storage` service to your namer. </services> ``` +```yml +services: + acme_demo.custom_namer: + class: Acme\DemoBundle\CatNamer + arguments: ["@security.token_storage"] +``` + Now you can use the service to get the logged user id and return the custom directory like below: ```php @@ -92,7 +99,7 @@ class CatNamer implements NamerInterface */ public function name(FileInterface $file) { - $userId = $tokenStorage->getToken()->getUser()->getId(); + $userId = $this->tokenStorage->getToken()->getUser()->getId(); return sprintf('%s/%s.%s', $userId, @@ -103,4 +110,4 @@ class CatNamer implements NamerInterface } ``` -Every file uploaded through the `Controller` of this mapping will be named with your new directory structure. \ No newline at end of file +Every file uploaded through the `Controller` of this mapping will be named with your new directory structure.
0
fb44610d0a5099616eb839bedf85f2321f0ee8ea
1up-lab/OneupUploaderBundle
Use r+b instead of rb+ mode (#304)
commit fb44610d0a5099616eb839bedf85f2321f0ee8ea Author: Lctrs <[email protected]> Date: Mon Dec 18 13:41:59 2017 +0100 Use r+b instead of rb+ mode (#304) diff --git a/Uploader/Storage/FlysystemStorage.php b/Uploader/Storage/FlysystemStorage.php index c3783ac..401a8d8 100644 --- a/Uploader/Storage/FlysystemStorage.php +++ b/Uploader/Storage/FlysystemStorage.php @@ -38,7 +38,7 @@ class FlysystemStorage implements StorageInterface $path = null === $path ? $name : sprintf('%s/%s', $path, $name); if ($file instanceof FilesystemFile) { - $stream = fopen($file->getPathname(), 'rb+'); + $stream = fopen($file->getPathname(), 'r+b'); $this->filesystem->putStream($path, $stream, array( 'mimetype' => $file->getMimeType() ));
0
07747b684d5ba0696134cacd0eebab746f4b48d8
1up-lab/OneupUploaderBundle
CS fixes for Commands
commit 07747b684d5ba0696134cacd0eebab746f4b48d8 Author: Jim Schmid <[email protected]> Date: Thu Jun 20 21:23:05 2013 +0200 CS fixes for Commands diff --git a/Command/ClearChunkCommand.php b/Command/ClearChunkCommand.php index f1df091..89660b7 100644 --- a/Command/ClearChunkCommand.php +++ b/Command/ClearChunkCommand.php @@ -15,10 +15,10 @@ class ClearChunkCommand extends ContainerAwareCommand ->setDescription('Clear chunks according to the max-age you defined in your configuration.') ; } - + protected function execute(InputInterface $input, OutputInterface $output) { $manager = $this->getContainer()->get('oneup_uploader.chunk_manager'); $manager->clear(); } -} \ No newline at end of file +} diff --git a/Command/ClearOrphansCommand.php b/Command/ClearOrphansCommand.php index 46dcfdc..9a1b913 100644 --- a/Command/ClearOrphansCommand.php +++ b/Command/ClearOrphansCommand.php @@ -15,10 +15,10 @@ class ClearOrphansCommand extends ContainerAwareCommand ->setDescription('Clear orphaned uploads according to the max-age you defined in your configuration.') ; } - + protected function execute(InputInterface $input, OutputInterface $output) { $manager = $this->getContainer()->get('oneup_uploader.orphanage_manager'); $manager->clear(); } -} \ No newline at end of file +}
0
ee4f159a981762183fa5193ff2eb060ab2e83852
1up-lab/OneupUploaderBundle
Merge pull request #43 from albenik/master Using default error_handler related to frontend
commit ee4f159a981762183fa5193ff2eb060ab2e83852 (from 156f67be4e81d80c5da18050b14bf91dfaa6c7cf) Merge: 156f67b 9917cd6 Author: Jim Schmid <[email protected]> Date: Sun Aug 11 01:03:58 2013 -0700 Merge pull request #43 from albenik/master Using default error_handler related to frontend diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index 6472e05..1c8ec39 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -72,7 +72,7 @@ class Configuration implements ConfigurationInterface ->arrayNode('disallowed_mimetypes') ->prototype('scalar')->end() ->end() - ->scalarNode('error_handler')->defaultValue('oneup_uploader.error_handler.noop')->end() + ->scalarNode('error_handler')->defaultNull()->end() ->scalarNode('max_size') ->defaultValue(\PHP_INT_MAX) ->info('Set max_size to -1 for gracefully downgrade this number to the systems max upload size.') diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index fa4cb90..fae9056 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -121,7 +121,9 @@ class OneupUploaderExtension extends Extension throw new ServiceNotFoundException('Empty controller class or name. If you really want to use a custom frontend implementation, be sure to provide a class and a name.'); } - $errorHandler = new Reference($mapping['error_handler']); + $errorHandler = is_null($mapping['error_handler']) ? + new Reference('oneup_uploader.error_handler.'.$mapping['frontend']) : + new Reference($mapping['error_handler']); // create controllers based on mapping $container diff --git a/Resources/config/errorhandler.xml b/Resources/config/errorhandler.xml index 025e38a..7bfb131 100644 --- a/Resources/config/errorhandler.xml +++ b/Resources/config/errorhandler.xml @@ -10,7 +10,14 @@ <services> <service id="oneup_uploader.error_handler.noop" class="%oneup_uploader.error_handler.noop.class%" public="false" /> + <service id="oneup_uploader.error_handler.fineuploader" class="%oneup_uploader.error_handler.noop.class%" public="false" /> <service id="oneup_uploader.error_handler.blueimp" class="%oneup_uploader.error_handler.blueimp.class%" public="false" /> + <service id="oneup_uploader.error_handler.uploadify" class="%oneup_uploader.error_handler.noop.class%" public="false" /> + <service id="oneup_uploader.error_handler.yui3" class="%oneup_uploader.error_handler.noop.class%" public="false" /> + <service id="oneup_uploader.error_handler.fancyupload" class="%oneup_uploader.error_handler.noop.class%" public="false" /> + <service id="oneup_uploader.error_handler.mooupload" class="%oneup_uploader.error_handler.noop.class%" public="false" /> + <service id="oneup_uploader.error_handler.plupload" class="%oneup_uploader.error_handler.noop.class%" public="false" /> + <service id="oneup_uploader.error_handler.custom" class="%oneup_uploader.error_handler.noop.class%" public="false" /> </services> </container>
0
f7b509f11761eb18d6bec1606b9875e05efa4f58
1up-lab/OneupUploaderBundle
Fixed typo.
commit f7b509f11761eb18d6bec1606b9875e05efa4f58 Author: Jim Schmid <[email protected]> Date: Wed Sep 18 12:25:03 2013 +0200 Fixed typo. diff --git a/Resources/doc/index.md b/Resources/doc/index.md index 29ccad1..fe69b15 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -106,7 +106,7 @@ So if you take the mapping described before, the generated route name would be ` * [Use FancyUpload](frontend_fancyupload.md) * [Use MooUpload](frontend_mooupload.md) * [Use Plupload](frontend_plupload.md) -* [Use Dropzone]|(frontend_dropzone.md) +* [Use Dropzone](frontend_dropzone.md) ## Next steps
0
70fdfdbdf72642d382ce62d966d2079cc3a39061
1up-lab/OneupUploaderBundle
Merge pull request #245 from deviprsd21/master Fix #238 (typo, ®equested a non-existent service)
commit 70fdfdbdf72642d382ce62d966d2079cc3a39061 (from bde473d4cadabc752e072ae8487bf8d9bd429d9c) Merge: bde473d 4b188af Author: David Greminger <[email protected]> Date: Wed May 4 11:09:49 2016 +0200 Merge pull request #245 from deviprsd21/master Fix #238 (typo, ®equested a non-existent service) diff --git a/Uploader/Orphanage/OrphanageManager.php b/Uploader/Orphanage/OrphanageManager.php index 9352b4e..9442712 100644 --- a/Uploader/Orphanage/OrphanageManager.php +++ b/Uploader/Orphanage/OrphanageManager.php @@ -32,7 +32,7 @@ class OrphanageManager // Really ugly solution to clearing the orphanage on gaufrette $class = $this->container->getParameter('oneup_uploader.orphanage.class'); if ($class === 'Oneup\UploaderBundle\Uploader\Storage\GaufretteOrphanageStorage') { - $chunkStorage = $this->container->get('oneup_uploader.chunks_storage '); + $chunkStorage = $this->container->get('oneup_uploader.chunks_storage'); $chunkStorage->clear($this->config['maxage'], $this->config['directory']); return;
0
3b43437a8c49a023ae702f6544a408bef25fd7bc
1up-lab/OneupUploaderBundle
Fixed wrong event name for persist
commit 3b43437a8c49a023ae702f6544a408bef25fd7bc Author: Jacek Jędrzejewski <[email protected]> Date: Mon Jun 17 17:54:26 2013 +0300 Fixed wrong event name for persist diff --git a/Controller/AbstractController.php b/Controller/AbstractController.php index 47e07a4..49bce30 100644 --- a/Controller/AbstractController.php +++ b/Controller/AbstractController.php @@ -76,7 +76,7 @@ abstract class AbstractController // dispatch post persist event (both the specific and the general) $postPersistEvent = new PostPersistEvent($uploaded, $response, $request, $this->type, $this->config); $dispatcher->dispatch(UploadEvents::POST_PERSIST, $postPersistEvent); - $dispatcher->dispatch(sprintf('%s.%s', UploadEvents::POST_UPLOAD, $this->type), $postPersistEvent); + $dispatcher->dispatch(sprintf('%s.%s', UploadEvents::POST_PERSIST, $this->type), $postPersistEvent); } }
0
2e926bd4ee1feda112d3a48ca2bb33735e133a53
1up-lab/OneupUploaderBundle
Add flysystem to Readme
commit 2e926bd4ee1feda112d3a48ca2bb33735e133a53 Author: Malte Blättermann <[email protected]> Date: Thu Sep 22 22:17:07 2016 +0200 Add flysystem to Readme diff --git a/README.md b/README.md index d0f6ed6..7f18c9a 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Features included: * Multiple file uploads handled by your chosen frontend library * Chunked uploads -* Supports [Gaufrette](https://github.com/KnpLabs/Gaufrette) and/or local filesystem +* Support for: [Gaufrette](https://github.com/KnpLabs/Gaufrette) / [Flysystem](https://github.com/thephpleague/flysystem) / local filesystem * Provides an orphanage for cleaning up orphaned files * Supports [Session upload progress & cancelation of uploads](http://php.net/manual/en/session.upload-progress.php) as of PHP 5.4 * Fully unit tested
0
60be4df970282762718043d5939a29fabb30bacf
1up-lab/OneupUploaderBundle
Test on 7.4 and prefer-lowest on 7.2 (#386)
commit 60be4df970282762718043d5939a29fabb30bacf Author: David Greminger <[email protected]> Date: Fri Oct 23 10:54:05 2020 +0200 Test on 7.4 and prefer-lowest on 7.2 (#386) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 321b549..26eb666 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,7 +16,7 @@ jobs: - name: Setup PHP uses: shivammathur/setup-php@v2 with: - php-version: 7.3 + php-version: 7.4 extensions: dom, fileinfo, filter, gd, hash, intl, json, mbstring, pcre, pdo, zlib tools: prestissimo coverage: none @@ -65,7 +65,7 @@ jobs: - name: Setup PHP uses: shivammathur/setup-php@v2 with: - php-version: 7.3 + php-version: 7.2 extensions: dom, fileinfo, filter, gd, hash, intl, json, mbstring, pcre, pdo_mysql, zlib tools: prestissimo coverage: none
0
2aabf5b9b91998f37a58ebe563072715936977cc
1up-lab/OneupUploaderBundle
Update custom_uploader.md Removed event dispatching from implementation example.
commit 2aabf5b9b91998f37a58ebe563072715936977cc Author: Jim Schmid <[email protected]> Date: Thu Jun 20 22:00:12 2013 +0300 Update custom_uploader.md Removed event dispatching from implementation example. diff --git a/Resources/doc/custom_uploader.md b/Resources/doc/custom_uploader.md index 6c4a845..20de413 100644 --- a/Resources/doc/custom_uploader.md +++ b/Resources/doc/custom_uploader.md @@ -46,15 +46,9 @@ class CustomUploader extends UploaderController // get file from request (your own logic) $file = ...; - try - { + try { $uploaded = $this->handleUpload($file); - - // dispatch POST_PERSIST AND POST_UPLOAD events - $this->dispatchEvents($uploaded, $response, $request); - } - catch(UploadException $e) - { + } catch(UploadException $e) { // return nothing return new JsonResponse(array()); } @@ -126,4 +120,4 @@ class FineUploaderResponse extends AbstractResponse ## Notes -It is highly recommended to use the internal and inherited methods `handleUpload` and `handleChunkedUpload` as these will mind your configuration file. Nonetheless; it is possible to overwrite the behaviour completely in your Controller class. \ No newline at end of file +It is highly recommended to use the internal and inherited methods `handleUpload` and `handleChunkedUpload` as these will mind your configuration file. Nonetheless; it is possible to overwrite the behaviour completely in your Controller class.
0
a408548b241f47af3539b2137c1817a21a51fde9
1up-lab/OneupUploaderBundle
Refactored Event dispatching (BC-break) * Moved dispatching to the upload* functions * Added a new Event which will be fired after a chunk has been uploaded This is a huge BC-break. It has to be done to address #20 though.
commit a408548b241f47af3539b2137c1817a21a51fde9 Author: Jim Schmid <[email protected]> Date: Thu Jun 20 19:46:46 2013 +0200 Refactored Event dispatching (BC-break) * Moved dispatching to the upload* functions * Added a new Event which will be fired after a chunk has been uploaded This is a huge BC-break. It has to be done to address #20 though. diff --git a/Controller/AbstractChunkedController.php b/Controller/AbstractChunkedController.php index de094cb..e343807 100644 --- a/Controller/AbstractChunkedController.php +++ b/Controller/AbstractChunkedController.php @@ -4,7 +4,11 @@ namespace Oneup\UploaderBundle\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\File\UploadedFile; + +use Oneup\UploaderBundle\UploadEvents; +use Oneup\UploaderBundle\Uploader\Response\ResponseInterface; use Oneup\UploaderBundle\Controller\AbstractController; +use Oneup\UploaderBundle\Event\PostChunkUploadEvent; abstract class AbstractChunkedController extends AbstractController { @@ -35,7 +39,7 @@ abstract class AbstractChunkedController extends AbstractController * * @param file The uploaded chunk. */ - protected function handleChunkedUpload(UploadedFile $file) + protected function handleChunkedUpload(UploadedFile $file, ResponseInterface $response, Request $request) { // get basic container stuff $request = $this->container->get('request'); @@ -47,12 +51,13 @@ abstract class AbstractChunkedController extends AbstractController // get information about this chunked request list($last, $uuid, $index, $orig) = $this->parseChunkedRequest($request); - $uploaded = $chunkManager->addChunk($uuid, $index, $file, $orig); + $chunk = $chunkManager->addChunk($uuid, $index, $file, $orig); + + $this->dispatchChunkEvents($chunk, $response, $request, $last); // if all chunks collected and stored, proceed // with reassembling the parts - if($last) - { + if ($last) { // we'll take the first chunk and append the others to it // this way we don't need another file in temporary space for assembling $chunks = $chunkManager->getChunks($uuid); @@ -66,11 +71,22 @@ abstract class AbstractChunkedController extends AbstractController // validate this entity and upload on success $this->validate($uploadedFile); - $uploaded = $this->handleUpload($uploadedFile); + $uploaded = $this->handleUpload($uploadedFile, $response, $request); $chunkManager->cleanup($path); } + } + + /** + * This function is a helper function which dispatches post chunk upload event. + */ + protected function dispatchChunkEvents($uploaded, ResponseInterface $response, Request $request, $isLast) + { + $dispatcher = $this->container->get('event_dispatcher'); - return $uploaded; + // dispatch post upload event (both the specific and the general) + $postUploadEvent = new PostChunkUploadEvent($uploaded, $response, $request, $isLast, $this->type, $this->config); + $dispatcher->dispatch(UploadEvents::POST_CHUNK_UPLOAD, $postUploadEvent); + $dispatcher->dispatch(sprintf('%s.%s', UploadEvents::POST_CHUNK_UPLOAD, $this->type), $postUploadEvent); } } \ No newline at end of file diff --git a/Controller/AbstractController.php b/Controller/AbstractController.php index 49bce30..bcbe763 100644 --- a/Controller/AbstractController.php +++ b/Controller/AbstractController.php @@ -44,7 +44,7 @@ abstract class AbstractController * @param UploadedFile The file to upload * @return File the actual file */ - protected function handleUpload(UploadedFile $file) + protected function handleUpload(UploadedFile $file, ResponseInterface $response, Request $request) { $this->validate($file); @@ -55,7 +55,7 @@ abstract class AbstractController // perform the real upload $uploaded = $this->storage->upload($file, $name); - return $uploaded; + $this->dispatchEvents($uploaded, $response, $request); } /** @@ -71,8 +71,7 @@ abstract class AbstractController $dispatcher->dispatch(UploadEvents::POST_UPLOAD, $postUploadEvent); $dispatcher->dispatch(sprintf('%s.%s', UploadEvents::POST_UPLOAD, $this->type), $postUploadEvent); - if(!$this->config['use_orphanage']) - { + if (!$this->config['use_orphanage']) { // dispatch post persist event (both the specific and the general) $postPersistEvent = new PostPersistEvent($uploaded, $response, $request, $this->type, $this->config); $dispatcher->dispatch(UploadEvents::POST_PERSIST, $postPersistEvent); diff --git a/Controller/BlueimpController.php b/Controller/BlueimpController.php index 981a4a4..e62ed31 100644 --- a/Controller/BlueimpController.php +++ b/Controller/BlueimpController.php @@ -23,15 +23,12 @@ class BlueimpController extends AbstractChunkedController { $file = $file[0]; - try - { - $uploaded = $chunked ? $this->handleChunkedUpload($file) : $this->handleUpload($file); - - // dispatch POST_PERSIST AND POST_UPLOAD events - $this->dispatchEvents($uploaded, $response, $request); - } - catch(UploadException $e) - { + try { + $chunked ? + $this->handleChunkedUpload($file, $response, $request) : + $this->handleUpload($file, $response, $request) + ; + } catch(UploadException $e) { // return nothing return new JsonResponse(array()); } diff --git a/Controller/FancyUploadController.php b/Controller/FancyUploadController.php index c2e32bd..30a58a8 100644 --- a/Controller/FancyUploadController.php +++ b/Controller/FancyUploadController.php @@ -20,7 +20,7 @@ class FancyUploadController extends AbstractController { try { - $uploaded = $this->handleUpload($file); + $uploaded = $this->handleUpload($file, $response, $request); // dispatch POST_PERSIST AND POST_UPLOAD events $this->dispatchEvents($uploaded, $response, $request); diff --git a/Controller/FineUploaderController.php b/Controller/FineUploaderController.php index 37aa0b4..c295234 100644 --- a/Controller/FineUploaderController.php +++ b/Controller/FineUploaderController.php @@ -25,10 +25,10 @@ class FineUploaderController extends AbstractChunkedController { try { - $uploaded = $chunked ? $this->handleChunkedUpload($file) : $this->handleUpload($file); - - // dispatch POST_PERSIST AND POST_UPLOAD events - $this->dispatchEvents($uploaded, $response, $request); + $chunked ? + $this->handleChunkedUpload($file, $response, $request) : + $this->handleUpload($file, $response, $request) + ; } catch(UploadException $e) { diff --git a/Controller/MooUploadController.php b/Controller/MooUploadController.php index 1b06878..1b2ec9b 100644 --- a/Controller/MooUploadController.php +++ b/Controller/MooUploadController.php @@ -33,8 +33,6 @@ class MooUploadController extends AbstractChunkedController try { - $uploaded = $chunked ? $this->handleChunkedUpload($file) : $this->handleUpload($file); - // fill response object $response = $this->response; @@ -42,9 +40,11 @@ class MooUploadController extends AbstractChunkedController $response->setSize($headers->get('content-length')); $response->setName($headers->get('x-file-name')); $response->setUploadedName($uploadFileName); - - // dispatch POST_PERSIST AND POST_UPLOAD events - $this->dispatchEvents($uploaded, $response, $request); + + $chunked ? + $this->handleChunkedUpload($file, $response, $request) : + $this->handleUpload($file, $response, $request) + ; } catch(UploadException $e) { diff --git a/Controller/PluploadController.php b/Controller/PluploadController.php index c445174..60501e9 100644 --- a/Controller/PluploadController.php +++ b/Controller/PluploadController.php @@ -23,10 +23,10 @@ class PluploadController extends AbstractChunkedController { try { - $uploaded = $chunked ? $this->handleChunkedUpload($file) : $this->handleUpload($file); - - // dispatch POST_PERSIST AND POST_UPLOAD events - $this->dispatchEvents($uploaded, $response, $request); + $chunked ? + $this->handleChunkedUpload($file, $response, $request) : + $this->handleUpload($file, $response, $request) + ; } catch(UploadException $e) { diff --git a/Controller/UploadifyController.php b/Controller/UploadifyController.php index ea18f52..88038a2 100644 --- a/Controller/UploadifyController.php +++ b/Controller/UploadifyController.php @@ -20,7 +20,7 @@ class UploadifyController extends AbstractController { try { - $uploaded = $this->handleUpload($file); + $uploaded = $this->handleUpload($file, $response, $request); // dispatch POST_PERSIST AND POST_UPLOAD events $this->dispatchEvents($uploaded, $response, $request); diff --git a/Controller/YUI3Controller.php b/Controller/YUI3Controller.php index b063e92..4475947 100644 --- a/Controller/YUI3Controller.php +++ b/Controller/YUI3Controller.php @@ -20,7 +20,7 @@ class YUI3Controller extends AbstractController { try { - $uploaded = $this->handleUpload($file); + $uploaded = $this->handleUpload($file, $response, $request); // dispatch POST_PERSIST AND POST_UPLOAD events $this->dispatchEvents($uploaded, $response, $request); diff --git a/Event/PostChunkUploadEvent.php b/Event/PostChunkUploadEvent.php new file mode 100644 index 0000000..7d5aacd --- /dev/null +++ b/Event/PostChunkUploadEvent.php @@ -0,0 +1,62 @@ +<?php + +namespace Oneup\UploaderBundle\Event; + +use Symfony\Component\EventDispatcher\Event; +use Symfony\Component\HttpFoundation\Request; +use Oneup\UploaderBundle\Uploader\Response\ResponseInterface; + +class PostChunkUploadEvent extends Event +{ + protected $file; + protected $request; + protected $type; + protected $response; + protected $config; + protected $isLast; + + public function __construct($chunk, ResponseInterface $response, Request $request, $isLast, $type, array $config) + { + $this->chunk = $chunk; + $this->request = $request; + $this->response = $response; + $this->isLast = $isLast; + $this->type = $type; + $this->config = $config; + } + + public function getChunk() + { + return $this->chunk; + } + + public function getRequest() + { + return $this->request; + } + + public function getType() + { + return $this->type; + } + + public function getResponse() + { + return $this->response; + } + + public function getConfig() + { + return $this->config; + } + + public function getIsLast() + { + return $this->isLast; + } + + public function isLast() + { + return $this->isLast; + } +} diff --git a/Resources/doc/events.md b/Resources/doc/events.md index 4edba13..a7a5ff5 100644 --- a/Resources/doc/events.md +++ b/Resources/doc/events.md @@ -6,6 +6,10 @@ For a list of general Events, you can always have a look at the `UploadEvents.ph * `oneup_uploader.post_upload` Will be dispatched after a file has been uploaded and moved. * `oneup_uploader.post_persist` The same as `oneup_uploader.post_upload` but will only be dispatched if no `Orphanage` is used. +In case you are using chunked uploads on your frontend, you can listen to: + +* `oneup_uploader.post_chunk_upload` Will be dispatched after a chunk has been uploaded (including the last and assembled one) + Moreover this bundles also dispatches some special kind of generic events you can listen to. * `oneup_uploader.post_upload.{mapping}` diff --git a/Tests/Controller/AbstractChunkedUploadTest.php b/Tests/Controller/AbstractChunkedUploadTest.php index a5dfc2e..dd434c6 100644 --- a/Tests/Controller/AbstractChunkedUploadTest.php +++ b/Tests/Controller/AbstractChunkedUploadTest.php @@ -2,7 +2,10 @@ namespace Oneup\UploaderBundle\Tests\Controller; +use Symfony\Component\EventDispatcher\Event; use Oneup\UploaderBundle\Tests\Controller\AbstractUploadTest; +use Oneup\UploaderBundle\UploadEvents; +use Oneup\UploaderBundle\Event\PostChunkUploadEvent; abstract class AbstractChunkedUploadTest extends AbstractUploadTest { @@ -31,4 +34,38 @@ abstract class AbstractChunkedUploadTest extends AbstractUploadTest $this->assertEquals(120, $file->getSize()); } } + + public function testEvents() + { + $endpoint = $this->helper->endpoint($this->getConfigKey()); + + // prepare listener data + $me = $this; + $chunkCount = 0; + $uploadCount = 0; + $chunkSize = $this->getNextFile(0)->getSize(); + + for($i = 0; $i < $this->total; $i ++) { + // each time create a new client otherwise the events won't get dispatched + $client = static::createClient(); + $dispatcher = $client->getContainer()->get('event_dispatcher'); + + $dispatcher->addListener(UploadEvents::POST_CHUNK_UPLOAD, function(PostChunkUploadEvent $event) use (&$chunkCount, $chunkSize, &$me) { + ++ $chunkCount; + + $chunk = $event->getChunk(); + + $me->assertEquals($chunkSize, $chunk->getSize()); + }); + + $dispatcher->addListener(UploadEvents::POST_UPLOAD, function(Event $event) use (&$uploadCount) { + ++ $uploadCount; + }); + + $client->request('POST', $endpoint, $this->getNextRequestParameters($i), array($this->getNextFile($i))); + } + + $this->assertEquals($this->total, $chunkCount); + $this->assertEquals(1, $uploadCount); + } } diff --git a/UploadEvents.php b/UploadEvents.php index b4e6aeb..73f5c93 100644 --- a/UploadEvents.php +++ b/UploadEvents.php @@ -4,7 +4,8 @@ namespace Oneup\UploaderBundle; final class UploadEvents { - const POST_PERSIST = 'oneup_uploader.post_persist'; - const POST_UPLOAD = 'oneup_uploader.post_upload'; - const VALIDATION = 'oneup_uploader.validation'; + const POST_PERSIST = 'oneup_uploader.post_persist'; + const POST_UPLOAD = 'oneup_uploader.post_upload'; + const POST_CHUNK_UPLOAD = 'oneup_uploader.post_chunk_upload'; + const VALIDATION = 'oneup_uploader.validation'; } \ No newline at end of file
0
a90b2001d447f348a9e35862e72727ea75e07a5d
1up-lab/OneupUploaderBundle
Added KnpGaufretteBundle to the list of dependencies.
commit a90b2001d447f348a9e35862e72727ea75e07a5d Author: Jim Schmid <[email protected]> Date: Mon Mar 11 15:26:47 2013 +0100 Added KnpGaufretteBundle to the list of dependencies. diff --git a/composer.json b/composer.json index 51ece7f..d82d5c8 100644 --- a/composer.json +++ b/composer.json @@ -28,9 +28,10 @@ }, "require": { - "symfony/finder": ">=2.0.16,<2.3-dev", - "symfony/filesystem": ">=2.0.16,<2.3-dev", - "valums/file-uploader": "3.3.*" + "symfony/finder": ">=2.0.16,<2.3-dev", + "symfony/filesystem": ">=2.0.16,<2.3-dev", + "knplabs/knp-gaufrette-bundle": "0.1.*", + "valums/file-uploader": "3.3.*" }, "autoload": {
0
6fad4515cfeee610eb54bdda8ebf8fdaa8c8aabf
1up-lab/OneupUploaderBundle
Readded symfony/finder to deps.
commit 6fad4515cfeee610eb54bdda8ebf8fdaa8c8aabf Author: Jim Schmid <[email protected]> Date: Fri Apr 5 20:10:18 2013 +0200 Readded symfony/finder to deps. diff --git a/composer.json b/composer.json index 27a5d81..1327e02 100644 --- a/composer.json +++ b/composer.json @@ -13,7 +13,8 @@ ], "require": { - "symfony/framework-bundle": "2.*" + "symfony/framework-bundle": "2.*", + "symfony/finder": ">=2.0.16,<2.3-dev" }, "suggest": {
0
e62d3c87c36a1c674427631360852111ea0a7259
1up-lab/OneupUploaderBundle
Added a cancel method to AbstractController.
commit e62d3c87c36a1c674427631360852111ea0a7259 Author: Jim Schmid <[email protected]> Date: Tue Jun 25 11:18:51 2013 +0200 Added a cancel method to AbstractController. diff --git a/Controller/AbstractController.php b/Controller/AbstractController.php index 4b8bf48..13b8eb2 100644 --- a/Controller/AbstractController.php +++ b/Controller/AbstractController.php @@ -49,6 +49,24 @@ abstract class AbstractController return new JsonResponse($value); } + + public function cancel() + { + $request = $this->container->get('request'); + $session = $this->container->get('session'); + + $prefix = ini_get('session.upload_progress.prefix'); + $name = ini_get('session.upload_progress.name'); + + $key = sprintf('%s.%s', $prefix, $request->get($name)); + + $progress = $session->get($key); + $progress['cancel_upload'] = false; + + $session->set($key, $progress); + + return new JsonResponse(true); + } /** * This internal function handles the actual upload process
0
e0b21208c623676bd54445a3bc1f2efcd896b7a2
1up-lab/OneupUploaderBundle
Fix doc (see #337)
commit e0b21208c623676bd54445a3bc1f2efcd896b7a2 Author: stoccc <[email protected]> Date: Tue Jun 5 10:30:32 2018 +0200 Fix doc (see #337) diff --git a/Resources/doc/progress.md b/Resources/doc/progress.md index f3a6833..3086b72 100644 --- a/Resources/doc/progress.md +++ b/Resources/doc/progress.md @@ -31,7 +31,7 @@ $('#fileupload').bind('fileuploadsend', function (e, data) { data.formData.push(progressObj); data.context.data('interval', setInterval(function () { - $.get('{{ oneup_uploader_progress("gallery") }}', $.param([progressObj]), function (result) { + $.post('{{ oneup_uploader_progress("gallery") }}', $.param([progressObj]), function (result) { e = $.Event( 'progress', {bubbles: false, cancelable: true}); $.extend(e, result); ($('#fileupload').data('blueimp-fileupload') ||
0
de8a6470e8af80aca809e40b87ec45ac8e3a4269
1up-lab/OneupUploaderBundle
Added custom progress function for BlueimpController.
commit de8a6470e8af80aca809e40b87ec45ac8e3a4269 Author: Jim Schmid <[email protected]> Date: Tue Jun 25 16:51:21 2013 +0200 Added custom progress function for BlueimpController. diff --git a/Controller/BlueimpController.php b/Controller/BlueimpController.php index 41736a2..607797b 100644 --- a/Controller/BlueimpController.php +++ b/Controller/BlueimpController.php @@ -36,6 +36,27 @@ class BlueimpController extends AbstractChunkedController return new JsonResponse($response->assemble()); } + public function progress() + { + $request = $this->container->get('request'); + $session = $this->container->get('session'); + + $prefix = ini_get('session.upload_progress.prefix'); + $name = ini_get('session.upload_progress.name'); + + // ref: https://github.com/blueimp/jQuery-File-Upload/wiki/PHP-Session-Upload-Progress + $key = sprintf('%s.%s', $prefix, $request->get($name)); + $value = $session->get($key); + + $progress = array( + 'lengthComputable' => true, + 'loaded' => $value['bytes_processed'], + 'total' => $value['content_length'] + ); + + return new JsonResponse($progress); + } + protected function parseChunkedRequest(Request $request) { $session = $this->container->get('session');
0
34e25ab7d29635d6985dd78abfe1f4a273fd5195
1up-lab/OneupUploaderBundle
Added a config-dump to configuration_reference.md
commit 34e25ab7d29635d6985dd78abfe1f4a273fd5195 Author: Jim Schmid <[email protected]> Date: Sun Apr 7 13:12:44 2013 +0200 Added a config-dump to configuration_reference.md diff --git a/Resources/doc/configuration_reference.md b/Resources/doc/configuration_reference.md index e69de29..18a156e 100644 --- a/Resources/doc/configuration_reference.md +++ b/Resources/doc/configuration_reference.md @@ -0,0 +1,28 @@ +Configuration Reference +======================= + +All available configuration options are listed below with their default values. + +``` yaml +oneup_uploader: + chunks: + maxage: 604800 + directory: ~ + orphanage: + maxage: 604800 + directory: ~ + mappings: # Required + + # Prototype + id: + storage: + service: ~ + type: filesystem + filesystem: ~ + directory: ~ + allowed_extensions: [] + disallowed_extensions: [] + max_size: 9223372036854775807 + use_orphanage: false + namer: oneup_uploader.namer.uniqid +``` \ No newline at end of file
0
98f1ca9ebfcde7477d6db9d98088ec9c21353434
1up-lab/OneupUploaderBundle
Introducing AbstractResponse which integrates the ArrayAccess interface.
commit 98f1ca9ebfcde7477d6db9d98088ec9c21353434 Author: Jim Schmid <[email protected]> Date: Tue Apr 9 21:50:05 2013 +0200 Introducing AbstractResponse which integrates the ArrayAccess interface. diff --git a/Uploader/Response/AbstractResponse.php b/Uploader/Response/AbstractResponse.php new file mode 100644 index 0000000..1e97d50 --- /dev/null +++ b/Uploader/Response/AbstractResponse.php @@ -0,0 +1,35 @@ +<?php + +namespace Oneup\UploaderBundle\Uploader\Response; + +use Oneup\UploaderBundle\Uploader\Response\ResponseInterface; + +abstract class AbstractResponse implements ResponseInterface +{ + protected $data; + + public function __construct() + { + $this->data = array(); + } + + abstract public function assemble(); + + public function offsetSet($offset, $value) + { + is_null($offset) ? $this->data[] = $value : $this->data[$offset] = $value; + } + public function offsetExists($offset) + { + return isset($this->data[$offset]); + } + public function offsetUnset($offset) + { + unset($this->data[$offset]); + } + + public function offsetGet($offset) + { + return isset($this->data[$offset]) ? $this->data[$offset] : null; + } +} \ No newline at end of file diff --git a/Uploader/Response/BlueimpResponse.php b/Uploader/Response/BlueimpResponse.php new file mode 100644 index 0000000..a4abe2d --- /dev/null +++ b/Uploader/Response/BlueimpResponse.php @@ -0,0 +1,2 @@ +<?php + diff --git a/Uploader/Response/FineUploaderResponse.php b/Uploader/Response/FineUploaderResponse.php index 489ae56..4b47e3c 100644 --- a/Uploader/Response/FineUploaderResponse.php +++ b/Uploader/Response/FineUploaderResponse.php @@ -2,19 +2,19 @@ namespace Oneup\UploaderBundle\Uploader\Response; -use Oneup\UploaderBundle\Uploader\Response\ResponseInterface; +use Oneup\UploaderBundle\Uploader\Response\AbstractResponse; -class FineUploaderResponse implements ResponseInterface +class FineUploaderResponse extends AbstractResponse { protected $success; protected $error; - protected $data; public function __construct() { $this->success = true; $this->error = null; - $this->data = array(); + + parent::__construct(); } public function assemble() @@ -33,24 +33,6 @@ class FineUploaderResponse implements ResponseInterface return $data; } - - public function offsetSet($offset, $value) - { - is_null($offset) ? $this->data[] = $value : $this->data[$offset] = $value; - } - public function offsetExists($offset) - { - return isset($this->data[$offset]); - } - public function offsetUnset($offset) - { - unset($this->data[$offset]); - } - - public function offsetGet($offset) - { - return isset($this->data[$offset]) ? $this->data[$offset] : null; - } public function setSuccess($success) {
0
9a207fa8b2f273fec8086341eb9b4ca51d672f8c
1up-lab/OneupUploaderBundle
Fix Symfony 5.3 deprecations (#408)
commit 9a207fa8b2f273fec8086341eb9b4ca51d672f8c Author: Ondřej Exner <[email protected]> Date: Wed Aug 4 13:29:51 2021 +0200 Fix Symfony 5.3 deprecations (#408) diff --git a/src/Controller/AbstractController.php b/src/Controller/AbstractController.php index d4bc8b3..8d77b50 100644 --- a/src/Controller/AbstractController.php +++ b/src/Controller/AbstractController.php @@ -19,7 +19,6 @@ use Symfony\Component\HttpFoundation\FileBag; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\RequestStack; -use Symfony\Component\HttpFoundation\Session\SessionInterface; use Symfony\Contracts\EventDispatcher\Event; use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; @@ -65,8 +64,7 @@ abstract class AbstractController { $request = $this->getRequest(); - /** @var SessionInterface $session */ - $session = $this->container->get('session'); + $session = $request->getSession(); $prefix = (string) ini_get('session.upload_progress.prefix'); $name = (string) ini_get('session.upload_progress.name'); @@ -83,8 +81,7 @@ abstract class AbstractController { $request = $this->getRequest(); - /** @var SessionInterface $session */ - $session = $this->container->get('session'); + $session = $request->getSession(); $prefix = (string) ini_get('session.upload_progress.prefix'); $name = (string) ini_get('session.upload_progress.name'); @@ -226,7 +223,9 @@ abstract class AbstractController $requestStack = $this->container->get('request_stack'); /** @var Request $request */ - $request = $requestStack->getMasterRequest(); + $request = method_exists($requestStack, 'getMainRequest') + ? $requestStack->getMainRequest() + : $requestStack->getMasterRequest(); return $request; } diff --git a/src/Controller/BlueimpController.php b/src/Controller/BlueimpController.php index 126584a..aa1c778 100644 --- a/src/Controller/BlueimpController.php +++ b/src/Controller/BlueimpController.php @@ -8,7 +8,6 @@ use Oneup\UploaderBundle\Uploader\Response\EmptyResponse; use Symfony\Component\HttpFoundation\File\Exception\UploadException; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; -use Symfony\Component\HttpFoundation\Session\SessionInterface; class BlueimpController extends AbstractChunkedController { @@ -38,8 +37,7 @@ class BlueimpController extends AbstractChunkedController { $request = $this->getRequest(); - /** @var SessionInterface $session */ - $session = $this->container->get('session'); + $session = $request->getSession(); $prefix = (string) ini_get('session.upload_progress.prefix'); $name = (string) ini_get('session.upload_progress.name'); @@ -59,8 +57,7 @@ class BlueimpController extends AbstractChunkedController protected function parseChunkedRequest(Request $request): array { - /** @var SessionInterface $session */ - $session = $this->container->get('session'); + $session = $request->getSession(); $headerRange = $request->headers->get('content-range'); $attachmentName = rawurldecode((string) preg_replace('/(^[^"]+")|("$)/', '', (string) $request->headers->get('content-disposition'))); diff --git a/src/Controller/PluploadController.php b/src/Controller/PluploadController.php index f4d6ef6..193e7b3 100644 --- a/src/Controller/PluploadController.php +++ b/src/Controller/PluploadController.php @@ -8,7 +8,6 @@ use Oneup\UploaderBundle\Uploader\Response\EmptyResponse; use Symfony\Component\HttpFoundation\File\Exception\UploadException; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; -use Symfony\Component\HttpFoundation\Session\SessionInterface; class PluploadController extends AbstractChunkedController { @@ -36,8 +35,7 @@ class PluploadController extends AbstractChunkedController protected function parseChunkedRequest(Request $request): array { - /** @var SessionInterface $session */ - $session = $this->container->get('session'); + $session = $request->getSession(); $orig = $request->get('name'); $index = (int) $request->get('chunk');
0
78d09f027e170c20f951b3c81f95e5d087e79fc6
1up-lab/OneupUploaderBundle
Added symfony/event-dispatcher to the list of requirements.
commit 78d09f027e170c20f951b3c81f95e5d087e79fc6 Author: Jim Schmid <[email protected]> Date: Wed Mar 13 11:08:26 2013 +0100 Added symfony/event-dispatcher to the list of requirements. diff --git a/composer.json b/composer.json index d82d5c8..6d97b50 100644 --- a/composer.json +++ b/composer.json @@ -30,6 +30,7 @@ "require": { "symfony/finder": ">=2.0.16,<2.3-dev", "symfony/filesystem": ">=2.0.16,<2.3-dev", + "symfony/event-dispatcher": "2.2.*", "knplabs/knp-gaufrette-bundle": "0.1.*", "valums/file-uploader": "3.3.*" },
0
49650bcd4a0fc236b9c1b1a40dabb4371db898f0
1up-lab/OneupUploaderBundle
Merge pull request #211 from domojonux/patch-1 Dispatch Validate event for the gallery
commit 49650bcd4a0fc236b9c1b1a40dabb4371db898f0 (from f26a7bbc5cd5995ab2f29b1103ffc9cbc778a968) Merge: f26a7bb 1db2821 Author: Jim Schmid <[email protected]> Date: Mon Feb 8 08:41:50 2016 +0100 Merge pull request #211 from domojonux/patch-1 Dispatch Validate event for the gallery diff --git a/Controller/AbstractController.php b/Controller/AbstractController.php index 01ae713..75d3518 100644 --- a/Controller/AbstractController.php +++ b/Controller/AbstractController.php @@ -175,6 +175,7 @@ abstract class AbstractController $event = new ValidationEvent($file, $this->getRequest(), $this->config, $this->type); $dispatcher->dispatch(UploadEvents::VALIDATION, $event); + $dispatcher->dispatch(sprintf('%s.%s', UploadEvents::VALIDATION, $this->type), $event); } /** commit 49650bcd4a0fc236b9c1b1a40dabb4371db898f0 (from 1db282127c8f43c664e714a51b4d7fe8ddaec453) Merge: f26a7bb 1db2821 Author: Jim Schmid <[email protected]> Date: Mon Feb 8 08:41:50 2016 +0100 Merge pull request #211 from domojonux/patch-1 Dispatch Validate event for the gallery diff --git a/.travis.yml b/.travis.yml index 1564c0e..c044e39 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,6 @@ language: php php: - - 5.3 - 5.4 - 5.5 - 5.6 diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index 3374889..276ddf3 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -22,7 +22,7 @@ class Configuration implements ConfigurationInterface ->addDefaultsIfNotSet() ->children() ->enumNode('type') - ->values(array('filesystem', 'gaufrette')) + ->values(array('filesystem', 'gaufrette', 'flysystem')) ->defaultValue('filesystem') ->end() ->scalarNode('filesystem')->defaultNull()->end() @@ -65,7 +65,7 @@ class Configuration implements ConfigurationInterface ->children() ->scalarNode('service')->defaultNull()->end() ->enumNode('type') - ->values(array('filesystem', 'gaufrette')) + ->values(array('filesystem', 'gaufrette', 'flysystem')) ->defaultValue('filesystem') ->end() ->scalarNode('filesystem')->defaultNull()->end() diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index 7f35224..4a471c5 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -13,6 +13,10 @@ use Symfony\Component\DependencyInjection\Loader; class OneupUploaderExtension extends Extension { protected $storageServices = array(); + + /** + * @var ContainerBuilder + */ protected $container; protected $config; @@ -141,31 +145,44 @@ class OneupUploaderExtension extends Extension $config = &$this->config['chunks']['storage']; $storageClass = sprintf('%%oneup_uploader.chunks_storage.%s.class%%', $config['type']); - if ($config['type'] === 'filesystem') { - $config['directory'] = is_null($config['directory']) ? - sprintf('%s/uploader/chunks', $this->container->getParameter('kernel.cache_dir')) : - $this->normalizePath($config['directory']) - ; - - $this->container - ->register('oneup_uploader.chunks_storage', sprintf('%%oneup_uploader.chunks_storage.%s.class%%', $config['type'])) - ->addArgument($config['directory']) - ; - } else { - $this->registerGaufretteStorage( - 'oneup_uploader.chunks_storage', - $storageClass, $config['filesystem'], - $config['sync_buffer_size'], - $config['stream_wrapper'], - $config['prefix'] - ); - - $this->container->setParameter('oneup_uploader.orphanage.class', 'Oneup\UploaderBundle\Uploader\Storage\GaufretteOrphanageStorage'); - - // enforce load distribution when using gaufrette as chunk - // torage to avoid moving files forth-and-back - $this->config['chunks']['load_distribution'] = true; + + switch($config['type']) { + case 'filesystem': + $config['directory'] = is_null($config['directory']) ? + sprintf('%s/uploader/chunks', $this->container->getParameter('kernel.cache_dir')) : + $this->normalizePath($config['directory']) + ; + + $this->container + ->register('oneup_uploader.chunks_storage', sprintf('%%oneup_uploader.chunks_storage.%s.class%%', $config['type'])) + ->addArgument($config['directory']) + ; + break; + case 'gaufrette': + case 'flysystem': + $this->registerFilesystem( + $config['type'], + 'oneup_uploader.chunks_storage', + $storageClass, $config['filesystem'], + $config['sync_buffer_size'], + $config['stream_wrapper'], + $config['prefix'] + ); + + $this->container->setParameter( + 'oneup_uploader.orphanage.class', + sprintf('Oneup\UploaderBundle\Uploader\Storage\%sOrphanageStorage', ucfirst($config['type'])) + ); + + // enforce load distribution when using gaufrette as chunk + // torage to avoid moving files forth-and-back + $this->config['chunks']['load_distribution'] = true; + break; + default: + throw new \InvalidArgumentException(sprintf('Filesystem "%s" is invalid', $config['type'])); + break; } + } protected function createStorageService(&$config, $key, $orphanage = false) @@ -181,26 +198,31 @@ class OneupUploaderExtension extends Extension $storageName = sprintf('oneup_uploader.storage.%s', $key); $storageClass = sprintf('%%oneup_uploader.storage.%s.class%%', $config['type']); - if ($config['type'] == 'filesystem') { - $config['directory'] = is_null($config['directory']) ? - sprintf('%s/../web/uploads/%s', $this->container->getParameter('kernel.root_dir'), $key) : - $this->normalizePath($config['directory']) - ; - - $this->container - ->register($storageName, $storageClass) - ->addArgument($config['directory']) - ; - } - - if ($config['type'] == 'gaufrette') { - $this->registerGaufretteStorage( - $storageName, - $storageClass, - $config['filesystem'], - $config['sync_buffer_size'], - $config['stream_wrapper'] - ); + switch ($config['type']) { + case 'filesystem': + $config['directory'] = is_null($config['directory']) ? + sprintf('%s/../web/uploads/%s', $this->container->getParameter('kernel.root_dir'), $key) : + $this->normalizePath($config['directory']) + ; + + $this->container + ->register($storageName, $storageClass) + ->addArgument($config['directory']) + ; + break; + case 'gaufrette': + case 'flysystem': + $this->registerFilesystem( + $config['type'], + $storageName, + $storageClass, + $config['filesystem'], + $config['sync_buffer_size'], + $config['stream_wrapper'] + ); + break; + default: + break; } $storageService = new Reference($storageName); @@ -227,12 +249,22 @@ class OneupUploaderExtension extends Extension return $storageService; } - protected function registerGaufretteStorage($key, $class, $filesystem, $buffer, $streamWrapper = null, $prefix = '') + protected function registerFilesystem($type, $key, $class, $filesystem, $buffer, $streamWrapper = null, $prefix = '') { - if(!class_exists('Gaufrette\\Filesystem')) - throw new InvalidArgumentException('You have to install Gaufrette in order to use it as a chunk storage service.'); + switch ($type) { + case 'gaufrette': + if (!class_exists('Gaufrette\\Filesystem')) { + throw new InvalidArgumentException('You have to install knplabs/knp-gaufrette-bundle in order to use it as a chunk storage service.'); + } + break; + case 'flysystem': + if (!class_exists('League\\Flysystem\\Filesystem')) { + throw new InvalidArgumentException('You have to install oneup/flysystem-bundle in order to use it as a chunk storage service.'); + } + break; + } - if(strlen($filesystem) <= 0) + if (strlen($filesystem) <= 0) throw new ServiceNotFoundException('Empty service name'); $streamWrapper = $this->normalizeStreamWrapper($streamWrapper); @@ -242,8 +274,7 @@ class OneupUploaderExtension extends Extension ->addArgument(new Reference($filesystem)) ->addArgument($this->getValueInBytes($buffer)) ->addArgument($streamWrapper) - ->addArgument($prefix) - ; + ->addArgument($prefix); } protected function getMaxUploadSize($input) diff --git a/README.md b/README.md index daa5eac..d0f6ed6 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,7 @@ The entry point of the documentation can be found in the file `Resources/docs/in Upgrade Notes ------------- +* Version **1.5.0** supports now [Flysystem](https://github.com/1up-lab/OneupFlysystemBundle) (Thank you @[lsv](https://github.com/lsv)! PR [#213](https://github.com/1up-lab/OneupUploaderBundle/pull/213)) and is no longer compatible with PHP 5.3 (it's [EOL](http://php.net/eol.php) since August 2014 anyway). * Version **v1.0.0** introduced some backward compatibility breaks. For a full list of changes, head to the [dedicated pull request](https://github.com/1up-lab/OneupUploaderBundle/pull/57). * If you're using chunked uploads consider upgrading from **v0.9.6** to **v0.9.7**. A critical issue was reported regarding the assembly of chunks. More information in ticket [#21](https://github.com/1up-lab/OneupUploaderBundle/issues/21#issuecomment-21560320). * Error management [changed](https://github.com/1up-lab/OneupUploaderBundle/pull/25) in Version **0.9.6**. You can now register an `ErrorHandler` per configured frontend. This comes bundled with some adjustments to the `blueimp` controller. More information is available in [the documentation](https://github.com/1up-lab/OneupUploaderBundle/blob/master/Resources/doc/custom_error_handler.md). diff --git a/Resources/config/uploader.xml b/Resources/config/uploader.xml index c970994..13d8f30 100644 --- a/Resources/config/uploader.xml +++ b/Resources/config/uploader.xml @@ -6,10 +6,12 @@ <parameters> <parameter key="oneup_uploader.chunks.manager.class">Oneup\UploaderBundle\Uploader\Chunk\ChunkManager</parameter> <parameter key="oneup_uploader.chunks_storage.gaufrette.class">Oneup\UploaderBundle\Uploader\Chunk\Storage\GaufretteStorage</parameter> + <parameter key="oneup_uploader.chunks_storage.flysystem.class">Oneup\UploaderBundle\Uploader\Chunk\Storage\FlysystemStorage</parameter> <parameter key="oneup_uploader.chunks_storage.filesystem.class">Oneup\UploaderBundle\Uploader\Chunk\Storage\FilesystemStorage</parameter> <parameter key="oneup_uploader.namer.uniqid.class">Oneup\UploaderBundle\Uploader\Naming\UniqidNamer</parameter> <parameter key="oneup_uploader.routing.loader.class">Oneup\UploaderBundle\Routing\RouteLoader</parameter> <parameter key="oneup_uploader.storage.gaufrette.class">Oneup\UploaderBundle\Uploader\Storage\GaufretteStorage</parameter> + <parameter key="oneup_uploader.storage.flysystem.class">Oneup\UploaderBundle\Uploader\Storage\FlysystemStorage</parameter> <parameter key="oneup_uploader.storage.filesystem.class">Oneup\UploaderBundle\Uploader\Storage\FilesystemStorage</parameter> <parameter key="oneup_uploader.orphanage.class">Oneup\UploaderBundle\Uploader\Storage\FilesystemOrphanageStorage</parameter> <parameter key="oneup_uploader.orphanage.manager.class">Oneup\UploaderBundle\Uploader\Orphanage\OrphanageManager</parameter> diff --git a/Resources/doc/chunked_uploads.md b/Resources/doc/chunked_uploads.md index fd6d87a..c577309 100644 --- a/Resources/doc/chunked_uploads.md +++ b/Resources/doc/chunked_uploads.md @@ -1,7 +1,7 @@ Using Chunked Uploads ===================== -Fine Uploader comes bundled with the possibility to use so called chunked uploads. If enabed, an uploaded file will be split into equal sized blobs which are sequentially uploaded afterwards. In order to use this feature, be sure to enable it in the frontend. +Fine Uploader comes bundled with the possibility to use so called chunked uploads. If enabled, an uploaded file will be split into equal sized blobs which are sequentially uploaded afterwards. In order to use this feature, be sure to enable it in the frontend. ```js $(document).ready(function() diff --git a/Resources/doc/custom_logic.md b/Resources/doc/custom_logic.md index ccb915e..6fea373 100644 --- a/Resources/doc/custom_logic.md +++ b/Resources/doc/custom_logic.md @@ -11,15 +11,21 @@ In almost every use case you need to further process uploaded files. For example To listen to one of these events you need to create an `EventListener`. ```php -namespace Acme\HelloBundle\EventListener; +namespace AppBundle\EventListener; +use Doctrine\Common\Persistence\ObjectManager; use Oneup\UploaderBundle\Event\PostPersistEvent; class UploadListener { - public function __construct($doctrine) + /** + * @var ObjectManager + */ + private $om; + + public function __construct(ObjectManager $om) { - $this->doctrine = $doctrine; + $this->om = $om; } public function onUpload(PostPersistEvent $event) @@ -33,7 +39,7 @@ And register it in your `services.xml`. ```xml <services> - <service id="acme_hello.upload_listener" class="Acme\HelloBundle\EventListener\UploadListener"> + <service id="app.upload_listener" class="AppBundle\EventListener\UploadListener"> <argument type="service" id="doctrine" /> <tag name="kernel.event_listener" event="oneup_uploader.post_persist" method="onUpload" /> </service> @@ -43,8 +49,8 @@ And register it in your `services.xml`. ```yml services: acme_hello.upload_listener: - class: Acme\HelloBundle\EventListener\UploadListener - argument: ["@doctrine"] + class: AppBundle\EventListener\UploadListener + argument: ["@doctrine.orm.entity_manager"] tags: - { name: kernel.event_listener, event: oneup_uploader.post_persist, method: onUpload } ``` @@ -114,6 +120,6 @@ use Symfony\Component\HttpFoundation\File\Exception\UploadException; public function onUpload(PostPersistEvent $event) { // Remember to remove the already uploaded file - throw new UploadException('Nope, I dont do files'); + throw new UploadException('Nope, I don\'t do files.'); } ``` diff --git a/Resources/doc/custom_namer.md b/Resources/doc/custom_namer.md index c83002d..256d2c6 100644 --- a/Resources/doc/custom_namer.md +++ b/Resources/doc/custom_namer.md @@ -10,7 +10,7 @@ First, create a custom namer which implements ```Oneup\UploaderBundle\Uploader\N ```php <?php -namespace Acme\DemoBundle; +namespace AppBundle\Uploader\Naming; use Oneup\UploaderBundle\Uploader\File\FileInterface; use Oneup\UploaderBundle\Uploader\Naming\NamerInterface; @@ -24,7 +24,7 @@ class CatNamer implements NamerInterface } ``` -To match the `NamerInterface` you have to implement the function `name()` which expects an `FileInterface` and should return a string representing the name of the given file. The example above would name every file _grumpycat.jpg_ and is therefore not very useful. +To match the `NamerInterface` you have to implement the function `name()` which expects an `FileInterface` and should return a string representing the name of the given file. The example above would name every file _grumpycat.jpg_ and is therefore not very useful. The namer should return an unique name to avoid issues if the file already exists. Next, register your created namer as a service in your `services.xml` @@ -36,8 +36,8 @@ Next, register your created namer as a service in your `services.xml` ```yml services: - acme_demo.custom_namer: - class: Acme\DemoBundle\CatNamer + app.cat_namer: + class: AppBundle\Uploader\Naming\CatNamer ``` Now you can use your custom service by adding it to your configuration: @@ -46,7 +46,7 @@ Now you can use your custom service by adding it to your configuration: oneup_uploader: mappings: gallery: - namer: acme_demo.custom_namer + namer: app.cat_namer ``` Every file uploaded through the `Controller` of this mapping will be named with your custom namer. diff --git a/Resources/doc/frontend_fineuploader.md b/Resources/doc/frontend_fineuploader.md index cd8a019..22fbb16 100644 --- a/Resources/doc/frontend_fineuploader.md +++ b/Resources/doc/frontend_fineuploader.md @@ -1,26 +1,27 @@ Use FineUploader ================ -Download [FineUploader](http://fineuploader.com/) and include it in your template. Connect the `endpoint` property to the dynamic route `_uploader_{mapping_name}`. +Download [FineUploader 5](http://fineuploader.com/) and include it in your template. Connect the `endpoint` property to the dynamic route `_uploader_{mapping_name}`. This example is based on the [UI Mode](http://docs.fineuploader.com/branch/master/quickstart/01-getting-started.html) of FineUploader. ```html -<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script> -<script type="text/javascript" src="js/jquery.fineuploader-3.4.1.js"></script> +<link href="fine-uploader/fine-uploader-new.min.css" rel="stylesheet"> +<script type="text/javascript" src="fine-uploader/fine-uploader.min.js"></script> <script type="text/javascript"> -$(document).ready(function() -{ var uploader = new qq.FineUploader({ - element: $('#uploader')[0], + element: document.getElementById('fine-uploader'), request: { endpoint: "{{ oneup_uploader_endpoint('gallery') }}" } }); -}); </script> -<div id="uploader"></div> +<div id="fine-uploader"></div> ``` +You can find a fully example of all available settings on the [official documentation](http://docs.fineuploader.com/branch/master/quickstart/02-setting_options.html). + +If you are using Fine Uploader UI, as described in this example, you **MUST** include a template in your document/markup. You can use the ``default.html`` file in the templates directory bundled with the FineUploader library and customize it as desired. You even can use an inline template. See the official [styling documentation page](http://docs.fineuploader.com/branch/master/features/styling.html) for more details. + Configure the OneupUploaderBundle to use the correct controller: ```yaml diff --git a/Resources/doc/index.md b/Resources/doc/index.md index 4178e9e..39ab715 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -34,19 +34,9 @@ Perform the following steps to install and use the basic functionality of the On Add OneupUploaderBundle to your composer.json using the following construct: -```js -{ - "require": { - "oneup/uploader-bundle": "~1.4" - } -} -``` - -Now tell composer to download the bundle by running the following command: - - $> php composer.phar update oneup/uploader-bundle + $ composer require oneup/uploader-bundle "~1.4" -Composer will now fetch and install this bundle in the vendor directory ```vendor/oneup``` +Composer will install the bundle to your project's ``vendor/oneup/uploader-bundle`` directory. ### Step 2: Enable the bundle diff --git a/Tests/Uploader/Storage/FlysystemOrphanageStorageTest.php b/Tests/Uploader/Storage/FlysystemOrphanageStorageTest.php new file mode 100644 index 0000000..a277d7e --- /dev/null +++ b/Tests/Uploader/Storage/FlysystemOrphanageStorageTest.php @@ -0,0 +1,119 @@ +<?php + +namespace Oneup\UploaderBundle\Tests\Uploader\Storage; + +use League\Flysystem\File; +use Oneup\UploaderBundle\Uploader\Chunk\Storage\FlysystemStorage as ChunkStorage; +use Oneup\UploaderBundle\Uploader\File\FlysystemFile; +use Oneup\UploaderBundle\Uploader\Storage\FlysystemOrphanageStorage; +use Symfony\Component\Filesystem\Filesystem; +use Symfony\Component\Finder\Finder; +use Symfony\Component\HttpFoundation\Session\Session; +use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage; + +use League\Flysystem\Adapter\Local as Adapter; +use League\Flysystem\Filesystem as FSAdapter; +use Oneup\UploaderBundle\Uploader\Storage\FlysystemStorage as Storage; + +class FlysystemOrphanageStorageTest extends OrphanageTest +{ + protected $chunkDirectory; + protected $chunksKey = 'chunks'; + protected $orphanageKey = 'orphanage'; + + public function setUp() + { + $this->numberOfPayloads = 5; + $this->realDirectory = sys_get_temp_dir() . '/storage'; + $this->chunkDirectory = $this->realDirectory .'/' . $this->chunksKey; + $this->tempDirectory = $this->realDirectory . '/' . $this->orphanageKey; + $this->payloads = array(); + + if (!$this->checkIfTempnameMatchesAfterCreation()) { + $this->markTestSkipped('Temporary directories do not match'); + } + + $filesystem = new Filesystem(); + $filesystem->mkdir($this->realDirectory); + $filesystem->mkdir($this->chunkDirectory); + $filesystem->mkdir($this->tempDirectory); + + $adapter = new Adapter($this->realDirectory, true); + $filesystem = new FSAdapter($adapter); + + $this->storage = new Storage($filesystem, 100000); + + $chunkStorage = new ChunkStorage($filesystem, 100000, null, 'chunks'); + + // create orphanage + $session = new Session(new MockArraySessionStorage()); + $session->start(); + + $config = array('directory' => 'orphanage'); + + $this->orphanage = new FlysystemOrphanageStorage($this->storage, $session, $chunkStorage, $config, 'cat'); + + for ($i = 0; $i < $this->numberOfPayloads; $i ++) { + // create temporary file as if it was reassembled by the chunk manager + $file = tempnam($this->chunkDirectory, 'uploader'); + + $pointer = fopen($file, 'w+'); + fwrite($pointer, str_repeat('A', 1024), 1024); + fclose($pointer); + + //gaufrette needs the key relative to it's root + $fileKey = str_replace($this->realDirectory, '', $file); + + $this->payloads[] = new FlysystemFile(new File($filesystem, $fileKey), $filesystem); + } + } + + public function testUpload() + { + for ($i = 0; $i < $this->numberOfPayloads; $i ++) { + $this->orphanage->upload($this->payloads[$i], $i . 'notsogrumpyanymore.jpeg'); + } + + $finder = new Finder(); + $finder->in($this->tempDirectory)->files(); + $this->assertCount($this->numberOfPayloads, $finder); + + $finder = new Finder(); + // exclude the orphanage and the chunks + $finder->in($this->realDirectory)->exclude(array($this->orphanageKey, $this->chunksKey))->files(); + $this->assertCount(0, $finder); + } + + public function testUploadAndFetching() + { + for ($i = 0; $i < $this->numberOfPayloads; $i ++) { + $this->orphanage->upload($this->payloads[$i], $i . 'notsogrumpyanymore.jpeg'); + } + + $finder = new Finder(); + $finder->in($this->tempDirectory)->files(); + $this->assertCount($this->numberOfPayloads, $finder); + + $finder = new Finder(); + $finder->in($this->realDirectory)->exclude(array($this->orphanageKey, $this->chunksKey))->files(); + $this->assertCount(0, $finder); + + $files = $this->orphanage->uploadFiles(); + + $this->assertTrue(is_array($files)); + $this->assertCount($this->numberOfPayloads, $files); + + $finder = new Finder(); + $finder->in($this->tempDirectory)->files(); + $this->assertCount(0, $finder); + + $finder = new Finder(); + $finder->in($this->realDirectory)->files(); + $this->assertCount($this->numberOfPayloads, $finder); + } + + public function checkIfTempnameMatchesAfterCreation() + { + return strpos(tempnam($this->chunkDirectory, 'uploader'), $this->chunkDirectory) === 0; + } +} diff --git a/Tests/Uploader/Storage/FlysystemStorageTest.php b/Tests/Uploader/Storage/FlysystemStorageTest.php new file mode 100644 index 0000000..bdd43e9 --- /dev/null +++ b/Tests/Uploader/Storage/FlysystemStorageTest.php @@ -0,0 +1,61 @@ +<?php + +namespace Oneup\UploaderBundle\Tests\Uploader\Storage; + +use League\Flysystem\Adapter\Local as Adapter; +use League\Flysystem\Filesystem as FSAdapter; +use Oneup\UploaderBundle\Uploader\File\FilesystemFile; +use Oneup\UploaderBundle\Uploader\Storage\FlysystemStorage as Storage; +use Symfony\Component\Finder\Finder; +use Symfony\Component\Filesystem\Filesystem; +use Symfony\Component\HttpFoundation\File\UploadedFile; + +class FlysystemStorageTest extends \PHPUnit_Framework_TestCase +{ + protected $directory; + + /** + * @var Storage + */ + protected $storage; + protected $file; + + public function setUp() + { + $this->directory = sys_get_temp_dir() . '/storage'; + + // create temporary file + $this->file = tempnam(sys_get_temp_dir(), 'uploader'); + + $pointer = fopen($this->file, 'w+'); + fwrite($pointer, str_repeat('A', 1024), 1024); + fclose($pointer); + + $adapter = new Adapter($this->directory, true); + $filesystem = new FSAdapter($adapter); + + $this->storage = new Storage($filesystem, 100000); + } + + public function testUpload() + { + $payload = new FilesystemFile(new UploadedFile($this->file, 'grumpycat.jpeg', null, null, null, true)); + $this->storage->upload($payload, 'notsogrumpyanymore.jpeg'); + + $finder = new Finder(); + $finder->in($this->directory)->files(); + + $this->assertCount(1, $finder); + + foreach ($finder as $file) { + $this->assertEquals($file->getFilename(), 'notsogrumpyanymore.jpeg'); + $this->assertEquals($file->getSize(), 1024); + } + } + + public function tearDown() + { + $filesystem = new Filesystem(); + $filesystem->remove($this->directory); + } +} diff --git a/Tests/Uploader/Storage/OrphanageTest.php b/Tests/Uploader/Storage/OrphanageTest.php index 836ab86..ce3f6cd 100644 --- a/Tests/Uploader/Storage/OrphanageTest.php +++ b/Tests/Uploader/Storage/OrphanageTest.php @@ -2,6 +2,7 @@ namespace Oneup\UploaderBundle\Tests\Uploader\Storage; +use Oneup\UploaderBundle\Uploader\Storage\FlysystemOrphanageStorage; use Symfony\Component\Finder\Finder; use Symfony\Component\Filesystem\Filesystem; @@ -9,6 +10,10 @@ abstract class OrphanageTest extends \PHPUnit_Framework_Testcase { protected $tempDirectory; protected $realDirectory; + + /** + * @var \Oneup\UploaderBundle\Uploader\Storage\OrphanageStorageInterface + */ protected $orphanage; protected $storage; protected $payloads; diff --git a/Uploader/Chunk/Storage/FlysystemStorage.php b/Uploader/Chunk/Storage/FlysystemStorage.php new file mode 100644 index 0000000..19e7a44 --- /dev/null +++ b/Uploader/Chunk/Storage/FlysystemStorage.php @@ -0,0 +1,152 @@ +<?php +namespace Oneup\UploaderBundle\Uploader\Chunk\Storage; + +use Oneup\UploaderBundle\Uploader\File\FlysystemFile; +use League\Flysystem\Filesystem; +use Symfony\Component\HttpFoundation\File\UploadedFile; + +class FlysystemStorage implements ChunkStorageInterface +{ + + protected $unhandledChunk; + protected $prefix; + protected $streamWrapperPrefix; + + /** + * @var Filesystem + */ + private $filesystem; + + public $bufferSize; + + public function __construct(Filesystem $filesystem, $bufferSize, $streamWrapperPrefix, $prefix) + { + if ( + ! method_exists($filesystem, 'readStream') + || + ! method_exists($filesystem, 'putStream') + ) { + throw new \InvalidArgumentException('The filesystem used as chunk storage must streamable'); + } + + $this->filesystem = $filesystem; + $this->bufferSize = $bufferSize; + $this->prefix = $prefix; + $this->streamWrapperPrefix = $streamWrapperPrefix; + } + + public function clear($maxAge, $prefix = null) + { + $prefix = $prefix ? :$this->prefix; + $matches = $this->filesystem->listFiles($prefix); + + $now = time(); + $toDelete = array(); + + // Collect the directories that are old, + // this also means the files inside are old + // but after the files are deleted the dirs + // would remain + foreach ($matches['dirs'] as $key) { + if ($maxAge <= $now-$this->filesystem->getTimestamp($key)) { + $toDelete[] = $key; + } + } + // The same directory is returned for every file it contains + array_unique($toDelete); + foreach ($matches['keys'] as $key) { + if ($maxAge <= $now-$this->filesystem->getTimestamp($key)) { + $this->filesystem->delete($key); + } + } + + foreach ($toDelete as $key) { + // The filesystem will throw exceptions if + // a directory is not empty + try { + $this->filesystem->delete($key); + } catch (\Exception $e) { + continue; + } + } + } + + public function addChunk($uuid, $index, UploadedFile $chunk, $original) + { + $this->unhandledChunk = array( + 'uuid' => $uuid, + 'index' => $index, + 'chunk' => $chunk, + 'original' => $original + ); + } + + public function assembleChunks($chunks, $removeChunk, $renameChunk) + { + // the index is only added to be in sync with the filesystem storage + $path = $this->prefix.'/'.$this->unhandledChunk['uuid'].'/'; + $filename = $this->unhandledChunk['index'].'_'.$this->unhandledChunk['original']; + + if (empty($chunks)) { + $target = $filename; + } else { + sort($chunks, SORT_STRING | SORT_FLAG_CASE); + $target = pathinfo($chunks[0], PATHINFO_BASENAME); + } + + + if ($this->unhandledChunk['index'] === 0) { + // if it's the first chunk overwrite the already existing part + // to avoid appending to earlier failed uploads + $handle = fopen($path . '/' . $target, 'w'); + } else { + $handle = fopen($path . '/' . $target, 'a'); + } + + $this->filesystem->putStream($path . $target, $handle); + if ($renameChunk) { + $name = preg_replace('/^(\d+)_/', '', $target); + /* The name can only match if the same user in the same session is + * trying to upload a file under the same name AND the previous upload failed, + * somewhere between this function, and the cleanup call. If that happened + * the previous file is unaccessible by the user, but if it is not removed + * it will block the user from trying to re-upload it. + */ + if ($this->filesystem->has($path.$name)) { + $this->filesystem->delete($path.$name); + } + + $this->filesystem->rename($path.$target, $path.$name); + $target = $name; + } + $uploaded = $this->filesystem->get($path.$target); + + if (!$renameChunk) { + return $uploaded; + } + + return new FlysystemFile($uploaded, $this->filesystem, $this->streamWrapperPrefix); + } + + public function cleanup($path) + { + $this->filesystem->delete($path); + } + + public function getChunks($uuid) + { + $results = $this->filesystem->listFiles($this->prefix.'/'.$uuid); + return preg_grep('/^.+\/(\d+)_/', $results['keys']); + } + + public function getFilesystem() + { + return $this->filesystem; + } + + public function getStreamWrapperPrefix() + { + return $this->streamWrapperPrefix; + } + +} diff --git a/Uploader/File/FlysystemFile.php b/Uploader/File/FlysystemFile.php new file mode 100644 index 0000000..dc36e69 --- /dev/null +++ b/Uploader/File/FlysystemFile.php @@ -0,0 +1,48 @@ +<?php +namespace Oneup\UploaderBundle\Uploader\File; + +use League\Flysystem\File; +use League\Flysystem\Filesystem; + +class FlysystemFile extends File implements FileInterface +{ + + protected $streamWrapperPrefix; + protected $mimeType; + + public function __construct(File $file, Filesystem $filesystem, $streamWrapperPrefix = null) + { + parent::__construct($filesystem, $file->getPath()); + $this->streamWrapperPrefix = $streamWrapperPrefix; + } + + /** + * Returns the path of the file + * + * @return string + */ + public function getPathname() + { + return $this->getPath(); + } + + /** + * Returns the basename of the file + * + * @return string + */ + public function getBasename() + { + return pathinfo($this->getPath(), PATHINFO_BASENAME); + } + + /** + * Returns the guessed extension of the file + * + * @return mixed + */ + public function getExtension() + { + return pathinfo($this->getPath(), PATHINFO_EXTENSION); + } +} diff --git a/Uploader/Gaufrette/StreamManager.php b/Uploader/Gaufrette/StreamManager.php index 58868b8..7fcc83a 100644 --- a/Uploader/Gaufrette/StreamManager.php +++ b/Uploader/Gaufrette/StreamManager.php @@ -25,11 +25,9 @@ class StreamManager protected function ensureRemotePathExists($path) { - // this is a somehow ugly workaround introduced - // because the stream-mode is not able to create - // subdirectories. - if(!$this->filesystem->has($path)) + if(!$this->filesystem->has($path)) { $this->filesystem->write($path, '', true); + } } protected function openStream(Stream $stream, $mode) diff --git a/Uploader/Storage/FlysystemOrphanageStorage.php b/Uploader/Storage/FlysystemOrphanageStorage.php new file mode 100644 index 0000000..d9947c3 --- /dev/null +++ b/Uploader/Storage/FlysystemOrphanageStorage.php @@ -0,0 +1,93 @@ +<?php + +namespace Oneup\UploaderBundle\Uploader\Storage; + +use League\Flysystem\File; +use Oneup\UploaderBundle\Uploader\Chunk\Storage\FlysystemStorage as ChunkStorage; +use Oneup\UploaderBundle\Uploader\File\FileInterface; +use Oneup\UploaderBundle\Uploader\File\FlysystemFile; +use Symfony\Component\HttpFoundation\Session\SessionInterface; + +class FlysystemOrphanageStorage extends FlysystemStorage implements OrphanageStorageInterface +{ + protected $storage; + protected $session; + protected $chunkStorage; + protected $config; + protected $type; + + /** + * @param StorageInterface $storage + * @param SessionInterface $session + * @param ChunkStorage $chunkStorage This class is only used if the gaufrette chunk storage is used. + * @param $config + * @param $type + */ + public function __construct(StorageInterface $storage, SessionInterface $session, ChunkStorage $chunkStorage, $config, $type) + { + /* + * initiate the storage on the chunk storage's filesystem + * the stream wrapper is useful for metadata. + */ + parent::__construct($chunkStorage->getFilesystem(), $chunkStorage->bufferSize, $chunkStorage->getStreamWrapperPrefix()); + + $this->storage = $storage; + $this->chunkStorage = $chunkStorage; + $this->session = $session; + $this->config = $config; + $this->type = $type; + } + + public function upload(FileInterface $file, $name, $path = null) + { + if(!$this->session->isStarted()) + throw new \RuntimeException('You need a running session in order to run the Orphanage.'); + + return parent::upload($file, $name, $this->getPath()); + } + + public function uploadFiles(array $files = null) + { + try { + if (null === $files) { + $files = $this->getFiles(); + } + $return = array(); + + foreach ($files as $key => $file) { + try { + $return[] = $this->storage->upload($file, str_replace($this->getPath(), '', $key)); + } catch (\Exception $e) { + // well, we tried. + continue; + } + } + + return $return; + } catch (\Exception $e) { + return array(); + } + } + + public function getFiles() + { + $keys = $this->chunkStorage->getFilesystem()->listFiles($this->getPath()); + $keys = $keys['keys']; + $files = array(); + + foreach ($keys as $key) { + // gotta pass the filesystem to both as you can't get it out from one.. + $files[$key] = new FlysystemFile(new File($this->chunkStorage->getFilesystem(), $key), $this->chunkStorage->getFilesystem()); + } + + return $files; + } + + protected function getPath() + { + // the storage is initiated in the root of the filesystem, from where the orphanage directory + // should be relative. + return sprintf('%s/%s/%s', $this->config['directory'], $this->session->getId(), $this->type); + } + +} diff --git a/Uploader/Storage/FlysystemStorage.php b/Uploader/Storage/FlysystemStorage.php new file mode 100644 index 0000000..4d0212d --- /dev/null +++ b/Uploader/Storage/FlysystemStorage.php @@ -0,0 +1,59 @@ +<?php + +namespace Oneup\UploaderBundle\Uploader\Storage; + +use League\Flysystem\Filesystem; +use Oneup\UploaderBundle\Uploader\File\FileInterface; +use Oneup\UploaderBundle\Uploader\File\FlysystemFile; +use Symfony\Component\Filesystem\Filesystem as LocalFilesystem; + +class FlysystemStorage implements StorageInterface +{ + + /** + * @var null|string + */ + protected $streamWrapperPrefix; + + /** + * @var float + */ + protected $bufferSize; + + /** + * @var Filesystem + */ + private $filesystem; + + public function __construct(Filesystem $filesystem, $bufferSize, $streamWrapperPrefix = null) + { + $this->filesystem = $filesystem; + $this->bufferSize = $bufferSize; + $this->streamWrapperPrefix = $streamWrapperPrefix; + } + + public function upload(FileInterface $file, $name, $path = null) + { + $path = is_null($path) ? $name : sprintf('%s/%s', $path, $name); + + if ($file instanceof FlysystemFile) { + if ($file->getFilesystem() == $this->filesystem) { + $file->getFilesystem()->rename($file->getPath(), $path); + + return new FlysystemFile($this->filesystem->get($path), $this->filesystem, $this->streamWrapperPrefix); + } + } + + $this->filesystem->put($name, file_get_contents($file)); + + if ($file instanceof FlysystemFile) { + $file->delete(); + } else { + $filesystem = new LocalFilesystem(); + $filesystem->remove($file->getPathname()); + } + + return new FlysystemFile($this->filesystem->get($path), $this->filesystem, $this->streamWrapperPrefix); + } + +} diff --git a/composer.json b/composer.json index b2f32a3..b0ef8ce 100644 --- a/composer.json +++ b/composer.json @@ -15,6 +15,7 @@ ], "require": { + "php":">=5.4", "symfony/framework-bundle": "^2.4.0|~3.0", "symfony/finder": "^2.4.0|~3.0" }, @@ -26,11 +27,13 @@ "symfony/security-bundle": "2.*|~3.0", "sensio/framework-extra-bundle": "2.*|~3.0", "symfony/browser-kit": "2.*|~3.0", - "phpunit/phpunit": "~4.4" + "phpunit/phpunit": "~4.4", + "oneup/flysystem-bundle": "^1.2" }, "suggest": { - "knplabs/knp-gaufrette-bundle": "0.1.*" + "knplabs/knp-gaufrette-bundle": "0.1.*", + "oneup/flysystem-bundle": "^1.2" }, "autoload": {
0
aec4bea577776783cd9417a10b9d936563f1f429
1up-lab/OneupUploaderBundle
Merge branch 'master' of https://github.com/snarktooth/OneupUploaderBundle into snarktooth-master
commit aec4bea577776783cd9417a10b9d936563f1f429 (from c5a1ce9a0e7b2f84982ccff39ba88832e0602cae) Merge: c5a1ce9 4b9eac4 Author: David Greminger <[email protected]> Date: Wed May 3 11:01:08 2017 +0200 Merge branch 'master' of https://github.com/snarktooth/OneupUploaderBundle into snarktooth-master diff --git a/Tests/Uploader/Storage/FlysystemOrphanageStorageTest.php b/Tests/Uploader/Storage/FlysystemOrphanageStorageTest.php index f78b1fc..102e954 100644 --- a/Tests/Uploader/Storage/FlysystemOrphanageStorageTest.php +++ b/Tests/Uploader/Storage/FlysystemOrphanageStorageTest.php @@ -29,15 +29,15 @@ class FlysystemOrphanageStorageTest extends OrphanageTest $this->tempDirectory = $this->realDirectory . '/' . $this->orphanageKey; $this->payloads = array(); - if (!$this->checkIfTempnameMatchesAfterCreation()) { - $this->markTestSkipped('Temporary directories do not match'); - } - $filesystem = new Filesystem(); $filesystem->mkdir($this->realDirectory); $filesystem->mkdir($this->chunkDirectory); $filesystem->mkdir($this->tempDirectory); + if (!$this->checkIfTempnameMatchesAfterCreation()) { + $this->markTestSkipped('Temporary directories do not match'); + } + $adapter = new Adapter($this->realDirectory, true); $filesystem = new FSAdapter($adapter); @@ -61,7 +61,7 @@ class FlysystemOrphanageStorageTest extends OrphanageTest fwrite($pointer, str_repeat('A', 1024), 1024); fclose($pointer); - //gaufrette needs the key relative to it's root + //file key needs to be relative to the root of the flysystem filesystem $fileKey = str_replace($this->realDirectory, '', $file); $this->payloads[] = new FlysystemFile(new File($filesystem, $fileKey), $filesystem); @@ -95,7 +95,9 @@ class FlysystemOrphanageStorageTest extends OrphanageTest $this->assertCount($this->numberOfPayloads, $finder); $finder = new Finder(); - $finder->in($this->realDirectory)->exclude(array($this->orphanageKey, $this->chunksKey))->files(); + $finder->in($this->realDirectory) + ->exclude(array($this->orphanageKey, $this->chunksKey)) + ->files(); $this->assertCount(0, $finder); $files = $this->orphanage->uploadFiles(); @@ -114,6 +116,10 @@ class FlysystemOrphanageStorageTest extends OrphanageTest public function checkIfTempnameMatchesAfterCreation() { - return strpos(@tempnam($this->chunkDirectory, 'uploader'), $this->chunkDirectory) === 0; + $testName = tempnam($this->chunkDirectory, 'uploader'); + $result = strpos($testName, $this->chunkDirectory) === 0; + unlink($testName); + + return $result; } } diff --git a/Uploader/Storage/FlysystemOrphanageStorage.php b/Uploader/Storage/FlysystemOrphanageStorage.php index d9947c3..376deb5 100644 --- a/Uploader/Storage/FlysystemOrphanageStorage.php +++ b/Uploader/Storage/FlysystemOrphanageStorage.php @@ -71,13 +71,19 @@ class FlysystemOrphanageStorage extends FlysystemStorage implements OrphanageSto public function getFiles() { - $keys = $this->chunkStorage->getFilesystem()->listFiles($this->getPath()); - $keys = $keys['keys']; + $fileList = $this->chunkStorage + ->getFilesystem() + ->listContents($this->getPath()); $files = array(); - foreach ($keys as $key) { - // gotta pass the filesystem to both as you can't get it out from one.. - $files[$key] = new FlysystemFile(new File($this->chunkStorage->getFilesystem(), $key), $this->chunkStorage->getFilesystem()); + foreach ($fileList as $fileDetail) { + $key = $fileDetail['path']; + if ($fileDetail['type'] == 'file') { + $files[$key] = new FlysystemFile( + new File($this->chunkStorage->getFilesystem(), $key), + $this->chunkStorage->getFilesystem() + ); + } } return $files; commit aec4bea577776783cd9417a10b9d936563f1f429 (from 4b9eac4d9a49dc5a14d4fd739d8f914af84ee4a6) Merge: c5a1ce9 4b9eac4 Author: David Greminger <[email protected]> Date: Wed May 3 11:01:08 2017 +0200 Merge branch 'master' of https://github.com/snarktooth/OneupUploaderBundle into snarktooth-master diff --git a/.travis.yml b/.travis.yml index c044e39..0e69924 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,6 +5,7 @@ php: - 5.5 - 5.6 - 7.0 + - 7.1 - hhvm env: @@ -20,6 +21,7 @@ matrix: allow_failures: - php: hhvm - php: 7.0 + - php: 7.1 - env: SYMFONY_VERSION=dev-master include: @@ -42,3 +44,5 @@ before_script: - composer selfupdate - composer require symfony/http-kernel:${SYMFONY_VERSION} --prefer-source - composer install --dev --prefer-source + +script: ./vendor/bin/phpunit diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index 276ddf3..75d64b4 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -90,6 +90,7 @@ class Configuration implements ConfigurationInterface ->booleanNode('enable_progress')->defaultFalse()->end() ->booleanNode('enable_cancelation')->defaultFalse()->end() ->scalarNode('namer')->defaultValue('oneup_uploader.namer.uniqid')->end() + ->booleanNode('root_folder')->defaultFalse()->end() ->end() ->end() ->end() diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index 4a471c5..c2c14eb 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -200,8 +200,11 @@ class OneupUploaderExtension extends Extension switch ($config['type']) { case 'filesystem': + // root_folder is true, remove the mapping name folder from path + $folder = $this->config['mappings'][$key]['root_folder'] ? '' : $key; + $config['directory'] = is_null($config['directory']) ? - sprintf('%s/../web/uploads/%s', $this->container->getParameter('kernel.root_dir'), $key) : + sprintf('%s/../web/uploads/%s', $this->container->getParameter('kernel.root_dir'), $folder) : $this->normalizePath($config['directory']) ; @@ -291,11 +294,14 @@ class OneupUploaderExtension extends Extension // see: http://www.php.net/manual/en/function.ini-get.php $input = trim($input); $last = strtolower($input[strlen($input) - 1]); + $numericInput = (float) substr($input, 0, -1); switch ($last) { - case 'g': $input *= 1024; - case 'm': $input *= 1024; - case 'k': $input *= 1024; + case 'g': $numericInput *= 1024; + case 'm': $numericInput *= 1024; + case 'k': $numericInput *= 1024; + + return $numericInput; } return $input; diff --git a/README.md b/README.md index d0f6ed6..1daa930 100644 --- a/README.md +++ b/README.md @@ -1,22 +1,23 @@ OneupUploaderBundle =================== -The OneupUploaderBundle for Symfony2 adds support for handling file uploads using one of the following Javascript libraries, or [your own implementation](https://github.com/1up-lab/OneupUploaderBundle/blob/master/Resources/doc/custom_uploader.md). +The OneupUploaderBundle for Symfony2 adds support for handling file uploads using one of the following JavaScript libraries, or [your own implementation](https://github.com/1up-lab/OneupUploaderBundle/blob/master/Resources/doc/custom_uploader.md). -* [FineUploader](http://fineuploader.com/) -* [jQuery File Uploader](http://blueimp.github.io/jQuery-File-Upload/) -* [YUI3 Uploader](http://yuilibrary.com/yui/docs/uploader/) -* [Uploadify](http://www.uploadify.com/) -* [FancyUpload](http://digitarald.de/project/fancyupload/) -* [MooUpload](https://github.com/juanparati/MooUpload) -* [Plupload](http://www.plupload.com/) * [Dropzone](http://www.dropzonejs.com/) +* [jQuery File Upload](http://blueimp.github.io/jQuery-File-Upload/) +* [Plupload](http://www.plupload.com/) +* [FineUploader](http://fineuploader.com/) +* [FancyUpload](http://digitarald.de/project/fancyupload/) (based on MooTools) +* [MooUpload](https://github.com/juanparati/MooUpload) (based on MooTools) +* [YUI3 Uploader](http://yuilibrary.com/yui/docs/uploader/) (the YUI library is no longer maintained) +* [UploadiFive](http://www.uploadify.com/) ($ 5.00) + Features included: * Multiple file uploads handled by your chosen frontend library * Chunked uploads -* Supports [Gaufrette](https://github.com/KnpLabs/Gaufrette) and/or local filesystem +* Support for: [Gaufrette](https://github.com/KnpLabs/Gaufrette) / [Flysystem](https://github.com/thephpleague/flysystem) / local filesystem * Provides an orphanage for cleaning up orphaned files * Supports [Session upload progress & cancelation of uploads](http://php.net/manual/en/session.upload-progress.php) as of PHP 5.4 * Fully unit tested diff --git a/Resources/config/errorhandler.xml b/Resources/config/errorhandler.xml index bf580bf..1f51fb2 100644 --- a/Resources/config/errorhandler.xml +++ b/Resources/config/errorhandler.xml @@ -12,7 +12,9 @@ <services> <service id="oneup_uploader.error_handler.noop" class="%oneup_uploader.error_handler.noop.class%" public="false" /> <service id="oneup_uploader.error_handler.fineuploader" class="%oneup_uploader.error_handler.noop.class%" public="false" /> - <service id="oneup_uploader.error_handler.blueimp" class="%oneup_uploader.error_handler.blueimp.class%" public="false" /> + <service id="oneup_uploader.error_handler.blueimp" class="%oneup_uploader.error_handler.blueimp.class%" public="false"> + <argument type="service" id="translator"/> + </service> <service id="oneup_uploader.error_handler.uploadify" class="%oneup_uploader.error_handler.noop.class%" public="false" /> <service id="oneup_uploader.error_handler.yui3" class="%oneup_uploader.error_handler.noop.class%" public="false" /> <service id="oneup_uploader.error_handler.fancyupload" class="%oneup_uploader.error_handler.noop.class%" public="false" /> diff --git a/Resources/doc/configuration_reference.md b/Resources/doc/configuration_reference.md index 6b0d248..a7cee8a 100644 --- a/Resources/doc/configuration_reference.md +++ b/Resources/doc/configuration_reference.md @@ -38,6 +38,7 @@ oneup_uploader: allowed_mimetypes: [] disallowed_mimetypes: [] error_handler: oneup_uploader.error_handler.noop + root_folder: false # Set max_size to -1 for gracefully downgrade this number to the systems max upload size. max_size: 9223372036854775807 diff --git a/Resources/doc/custom_logic.md b/Resources/doc/custom_logic.md index 1aa1cfd..3471492 100644 --- a/Resources/doc/custom_logic.md +++ b/Resources/doc/custom_logic.md @@ -31,6 +31,11 @@ class UploadListener public function onUpload(PostPersistEvent $event) { //... + + //if everything went fine + $response = $event->getResponse(); + $response['success'] = true; + return $response; } } ``` diff --git a/Resources/doc/custom_namer.md b/Resources/doc/custom_namer.md index 256d2c6..fea6ee0 100644 --- a/Resources/doc/custom_namer.md +++ b/Resources/doc/custom_namer.md @@ -50,3 +50,64 @@ oneup_uploader: ``` Every file uploaded through the `Controller` of this mapping will be named with your custom namer. + +## Change the directory structure + +With the `NameInterface` you can change the directory structure to provide a better files organization or to use your own existing structure. For example, you need to separate the uploaded files by users with a `user_id` folder. + +You need to inject the `security.token_storage` service to your namer. + +```xml +<services> + <service id="acme_demo.custom_namer" class="Acme\DemoBundle\CatNamer"> + <argument type="service" id="security.token_storage"/> + </service> +</services> +``` + +```yml +services: + acme_demo.custom_namer: + class: Acme\DemoBundle\CatNamer + arguments: ["@security.token_storage"] +``` + +Now you can use the service to get the logged user id and return the custom directory like below: + +```php +<?php + +namespace Acme\DemoBundle; + +use Oneup\UploaderBundle\Uploader\File\FileInterface; +use Oneup\UploaderBundle\Uploader\Naming\NamerInterface; +use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage; + +class CatNamer implements NamerInterface +{ + private $tokenStorage; + + public function __construct(TokenStorage $tokenStorage){ + $this->tokenStorage = $tokenStorage; + } + + /** + * Creates a user directory name for the file being uploaded. + * + * @param FileInterface $file + * @return string The directory name. + */ + public function name(FileInterface $file) + { + $userId = $this->tokenStorage->getToken()->getUser()->getId(); + + return sprintf('%s/%s.%s', + $userId, + uniqid(), + $file->getExtension() + ); + } +} +``` + +Every file uploaded through the `Controller` of this mapping will be named with your new directory structure. diff --git a/Resources/doc/flysystem_storage.md b/Resources/doc/flysystem_storage.md new file mode 100644 index 0000000..76aa1ea --- /dev/null +++ b/Resources/doc/flysystem_storage.md @@ -0,0 +1,75 @@ +Use Flysystem as Storage layer +============================== + +Flysystem is an abstract storage layer you can use to store your uploaded files. An explanation why you should use an abstraction storage layer comes from the _Why use Gaufrette_ section on [the Gaufrette Repo](https://github.com/KnpLabs/Gaufrette): + +> The filesystem abstraction layer permits you to develop your application without the need to know were all those medias will be stored and how. +> +> Another advantage of this is the possibility to update the files location without any impact on the code apart from the definition of your filesystem. In example, if your project grows up very fast and if your server reaches its limits, you can easily move your medias in an Amazon S3 server or any other solution. + +In order to use Flysystem with OneupUploaderBundle, be sure to follow these steps: + +## Install OneupFlysystemBundle + +Add the OneupFlysystemBundle to your composer.json file. + +```js +{ + "require": { + "oneup/flysystem-bundle": "1.4.*" + } +} +``` + +And update your dependencies through composer. + + $> php composer.phar update oneup/flysystem-bundle + +After installing, enable the bundle in your AppKernel: + +``` php +<?php +// app/AppKernel.php + +public function registerBundles() +{ + $bundles = array( + // ... + new Oneup\FlysystemBundle\OneupFlysystemBundle(), + ); +} +``` + +## Configure your Filesystems + +The following is a sample configuration for the OneupFlysystemBundle. It will create a flysystem service called `oneup_flysystem.gallery_filesystem` which can be used in the OneupUploaderBundle. For a complete list of features refer to the [official documentation](https://github.com/1up-lab/OneupFlysystemBundle). + +```yml +# app/config/config.yml + +oneup_flysystem: + adapters: + acme.flysystem_adapter: + awss3v3: + client: acme.s3_client + bucket: ~ + prefix: ~ + filesystems: + gallery: + adapter: acme.flysystem_adapter +``` + +## Configure your mappings + +Activate Flysystem by switching the `type` property to `flysystem` and pass the Flysystem filesystem configured in the previous step. + +```yml +# app/config/config.yml + +oneup_uploader: + mappings: + gallery: + storage: + type: flysystem + filesystem: oneup_flysystem.gallery_filesystem +``` diff --git a/Resources/doc/frontend_dropzone.md b/Resources/doc/frontend_dropzone.md index b0fd9b1..875fb3d 100644 --- a/Resources/doc/frontend_dropzone.md +++ b/Resources/doc/frontend_dropzone.md @@ -4,9 +4,9 @@ Use Dropzone in your Symfony2 application Download [Dropzone](http://www.dropzonejs.com/) and include it in your template. Connect the `action` property of the form to the dynamic route `_uploader_{mapping_name}`. ```html -<script type="text/javascript" src="https://raw.githubusercontent.com/enyo/dropzone/master/dist/dropzone.js"></script> +<script type="text/javascript" src="https://raw.github.com/enyo/dropzone/master/dist/dropzone.js"></script> -<form action="{{ oneup_uploader_endpoint('gallery') }}" class="dropzone"> +<form action="{{ oneup_uploader_endpoint('gallery') }}" class="dropzone" style="width:200px; height:200px; border:4px dashed black"> </form> ``` diff --git a/Resources/doc/index.md b/Resources/doc/index.md index 5fd3425..3942d44 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -65,7 +65,7 @@ This bundle was designed to just work out of the box. The only thing you have to oneup_uploader: mappings: gallery: - frontend: blueimp # or any uploader you use in the frontend + frontend: dropzone # or any uploader you use in the frontend ``` To enable the dynamic routes, add the following to your routing configuration file. @@ -78,13 +78,43 @@ oneup_uploader: type: uploader ``` -The default directory that is used to upload files to is `web/uploads/{mapping_name}`. +The default directory that is used to upload files to is `web/uploads/{mapping_name}`. In case you want to avoid a separated mapping folder, you can set `root_folder: true` and the default directory will be `web/uploads`. + +```yaml +# app/config/config.yml + +oneup_uploader: + mappings: + gallery: + root_folder: true +``` > It was reported that in some cases this directory was not created automatically. Please double check its existance if the upload does not work for you. +> You can improve the directory structure checking the "[Change the directory structure](custom_namer.md#change-the-directory-structure)". + +If you want to use your own path, for example /data/uploads : + +```yaml +# app/config/config.yml + +oneup_uploader: + mappings: + gallery: + storage: + directory: "%kernel.root_dir%/../data/uploads/" +``` + +### Step 4: Check if the bundle is working correctly + +No matter which JavaScript library you are going to use ultimately, we recommend to test the bundle with Dropzone first, since this one features the easiest setup process: -### Step 4: Prepare your frontend +1. [Install Dropzone](frontend_dropzone.md) +1. Drag a file onto the dashed rectangle. The upload should start immediately. However, you won't get any visual feedback yet. +1. Check your `web/uploads/gallery` directory: If you see the file there, the OneupUploaderBundle is working correctly. If you don't have that folder, create it manually and try again. -No matter what library you choose, be sure to connect the corresponding endpoint property to the dynamic route created from your mapping. To get a url for a specific mapping you can use the `oneup_uploader.templating.uploader_helper` service as follows: +### Step 5: Prepare your real frontend + +Now it's up to you to decide for a JavaScript library or write your own. Be sure to connect the corresponding endpoint property to the dynamic route created from your mapping. To get a url for a specific mapping you can use the `oneup_uploader.templating.uploader_helper` service as follows: ```php $helper = $this->container->get('oneup_uploader.templating.uploader_helper'); @@ -97,14 +127,14 @@ or in a Twig template you can use the `oneup_uploader_endpoint` function: So if you take the mapping described before, the generated route name would be `_uploader_gallery`. Follow one of the listed guides to include your frontend: -* [Use FineUploader](frontend_fineuploader.md) +* [Use Dropzone](frontend_dropzone.md) * [Use jQuery File Upload](frontend_blueimp.md) -* [Use YUI3 Uploader](frontend_yui3.md) -* [Use Uploadify](frontend_uploadify.md) +* [Use Plupload](frontend_plupload.md) +* [Use FineUploader](frontend_fineuploader.md) * [Use FancyUpload](frontend_fancyupload.md) * [Use MooUpload](frontend_mooupload.md) -* [Use Plupload](frontend_plupload.md) -* [Use Dropzone](frontend_dropzone.md) +* [Use YUI3 Uploader](frontend_yui3.md) +* [Use Uploadify](frontend_uploadify.md) ## Next steps @@ -115,6 +145,7 @@ some more advanced features. * [Return custom data to frontend](response.md) * [Enable chunked uploads](chunked_uploads.md) * [Using the Orphanage](orphanage.md) +* [Use Flysystem as storage layer](flysystem_storage.md) * [Use Gaufrette as storage layer](gaufrette_storage.md) * [Include your own Namer](custom_namer.md) * [Use custom error handlers](custom_error_handler.md) diff --git a/Tests/Controller/BlueimpValidationTest.php b/Tests/Controller/BlueimpValidationTest.php index 7ba1307..871e687 100644 --- a/Tests/Controller/BlueimpValidationTest.php +++ b/Tests/Controller/BlueimpValidationTest.php @@ -2,6 +2,7 @@ namespace Oneup\UploaderBundle\Tests\Controller; +use Symfony\Bundle\FrameworkBundle\Client; use Symfony\Component\HttpFoundation\File\UploadedFile; use Oneup\UploaderBundle\Tests\Controller\AbstractValidationTest; use Oneup\UploaderBundle\UploadEvents; @@ -11,6 +12,7 @@ class BlueimpValidationTest extends AbstractValidationTest public function testAgainstMaxSize() { // assemble a request + /** @var Client $client */ $client = $this->client; $endpoint = $this->helper->endpoint($this->getConfigKey()); @@ -20,6 +22,7 @@ class BlueimpValidationTest extends AbstractValidationTest //$this->assertTrue($response->isNotSuccessful()); $this->assertEquals($response->headers->get('Content-Type'), 'application/json'); $this->assertCount(0, $this->getUploadedFiles()); + $this->assertFalse(strpos($response->getContent(), 'error.maxsize'), "Failed to translate error id into lang"); } public function testEvents() diff --git a/Tests/Uploader/Storage/GaufretteOrphanageStorageTest.php b/Tests/Uploader/Storage/GaufretteOrphanageStorageTest.php index 418298c..a9e55cb 100644 --- a/Tests/Uploader/Storage/GaufretteOrphanageStorageTest.php +++ b/Tests/Uploader/Storage/GaufretteOrphanageStorageTest.php @@ -113,6 +113,6 @@ class GaufretteOrphanageStorageTest extends OrphanageTest public function checkIfTempnameMatchesAfterCreation() { - return strpos(tempnam($this->chunkDirectory, 'uploader'), $this->chunkDirectory) === 0; + return strpos(@tempnam($this->chunkDirectory, 'uploader'), $this->chunkDirectory) === 0; } } diff --git a/Tests/Uploader/Storage/OrphanageTest.php b/Tests/Uploader/Storage/OrphanageTest.php index ce3f6cd..c539e7f 100644 --- a/Tests/Uploader/Storage/OrphanageTest.php +++ b/Tests/Uploader/Storage/OrphanageTest.php @@ -6,7 +6,7 @@ use Oneup\UploaderBundle\Uploader\Storage\FlysystemOrphanageStorage; use Symfony\Component\Finder\Finder; use Symfony\Component\Filesystem\Filesystem; -abstract class OrphanageTest extends \PHPUnit_Framework_Testcase +abstract class OrphanageTest extends \PHPUnit_Framework_TestCase { protected $tempDirectory; protected $realDirectory; diff --git a/Uploader/ErrorHandler/BlueimpErrorHandler.php b/Uploader/ErrorHandler/BlueimpErrorHandler.php index c8839b7..be5e088 100644 --- a/Uploader/ErrorHandler/BlueimpErrorHandler.php +++ b/Uploader/ErrorHandler/BlueimpErrorHandler.php @@ -5,12 +5,23 @@ namespace Oneup\UploaderBundle\Uploader\ErrorHandler; use Exception; use Oneup\UploaderBundle\Uploader\ErrorHandler\ErrorHandlerInterface; use Oneup\UploaderBundle\Uploader\Response\AbstractResponse; +use Symfony\Component\Translation\TranslatorInterface; class BlueimpErrorHandler implements ErrorHandlerInterface { + /** + * @var TranslatorInterface + */ + private $translator; + + public function __construct(TranslatorInterface $translator) + { + $this->translator = $translator; + } + public function addException(AbstractResponse $response, Exception $exception) { - $message = $exception->getMessage(); + $message = $this->translator->trans($exception->getMessage(), array(), 'OneupUploaderBundle'); $response->addToOffset(array('error' => $message), array('files')); } } diff --git a/Uploader/Storage/FilesystemOrphanageStorage.php b/Uploader/Storage/FilesystemOrphanageStorage.php index ed6e4f6..8888e16 100644 --- a/Uploader/Storage/FilesystemOrphanageStorage.php +++ b/Uploader/Storage/FilesystemOrphanageStorage.php @@ -48,7 +48,7 @@ class FilesystemOrphanageStorage extends FilesystemStorage implements OrphanageS $return = array(); foreach ($files as $file) { - $return[] = $this->storage->upload(new FilesystemFile(new File($file->getPathname())), str_replace($this->getFindPath(), '', $file)); + $return[] = $this->storage->upload(new FilesystemFile(new File($file->getPathname())), ltrim(str_replace($this->getFindPath(), '', $file), "/")); } return $return;
0
7cb178103ce4e61f609426eb6bc961d593864aea
1up-lab/OneupUploaderBundle
Added the possibility to validate an uploaded file against its mimetype.
commit 7cb178103ce4e61f609426eb6bc961d593864aea Author: Jim Schmid <[email protected]> Date: Tue Apr 23 21:12:16 2013 +0200 Added the possibility to validate an uploaded file against its mimetype. diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index 89051cd..5c713c0 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -64,6 +64,9 @@ class Configuration implements ConfigurationInterface ->arrayNode('disallowed_extensions') ->prototype('scalar')->end() ->end() + ->arrayNode('allowed_mimetypes') + ->prototype('scalar')->end() + ->end() ->scalarNode('max_size')->defaultValue(\PHP_INT_MAX)->end() ->booleanNode('use_orphanage')->defaultFalse()->end() ->scalarNode('namer')->defaultValue('oneup_uploader.namer.uniqid')->end() diff --git a/EventListener/AllowedMimetypeValidationListener.php b/EventListener/AllowedMimetypeValidationListener.php new file mode 100644 index 0000000..62bfa93 --- /dev/null +++ b/EventListener/AllowedMimetypeValidationListener.php @@ -0,0 +1,26 @@ +<?php + +namespace Oneup\UploaderBundle\EventListener; + +use Oneup\UploaderBundle\Event\ValidationEvent; +use Oneup\UploaderBundle\Uploader\Exception\ValidationException; + +class AllowedMimetypeValidationListener +{ + public function onValidate(ValidationEvent $event) + { + $config = $event->getConfig(); + $file = $event->getFile(); + + if(count($config['allowed_mimetypes']) == 0) { + return; + } + + $finfo = finfo_open(FILEINFO_MIME_TYPE); + $mimetype = finfo_file($finfo, $file->getRealpath()); + + if(!in_array($mimetype, $config['allowed_mimetypes'])) { + throw new ValidationException('error.whitelist'); + } + } +} diff --git a/Resources/config/validators.xml b/Resources/config/validators.xml index 022dfbe..51b1449 100644 --- a/Resources/config/validators.xml +++ b/Resources/config/validators.xml @@ -15,6 +15,10 @@ <service id="oneup_uploader.validation_listener.disallowed_extension" class="Oneup\UploaderBundle\EventListener\DisallowedExtensionValidationListener"> <tag name="kernel.event_listener" event="oneup_uploader.validation" method="onValidate" /> </service> + + <service id="oneup_uploader.validation_listener.allowed_mimetype" class="Oneup\UploaderBundle\EventListener\AllowedMimetypeValidationListener"> + <tag name="kernel.event_listener" event="oneup_uploader.validation" method="onValidate" /> + </service> </services> </container>
0
f64018fc329f570fe47652066b15edce79f86021
1up-lab/OneupUploaderBundle
Merge pull request #100 from ribeiropaulor/bugfix_aws3_adapter bugfix: when using AwsS3 adapter the mimeType was not being set.
commit f64018fc329f570fe47652066b15edce79f86021 (from 9f7f3fbe988d3df5e0f6fc68b82b34cf1445a406) Merge: 9f7f3fb 5904a41 Author: Jim Schmid <[email protected]> Date: Tue Apr 8 10:15:36 2014 +0200 Merge pull request #100 from ribeiropaulor/bugfix_aws3_adapter bugfix: when using AwsS3 adapter the mimeType was not being set. diff --git a/Uploader/File/GaufretteFile.php b/Uploader/File/GaufretteFile.php index 0b6904b..73fc147 100644 --- a/Uploader/File/GaufretteFile.php +++ b/Uploader/File/GaufretteFile.php @@ -5,6 +5,7 @@ namespace Oneup\UploaderBundle\Uploader\File; use Gaufrette\Adapter\StreamFactory; use Gaufrette\File; use Gaufrette\Filesystem; +use \Gaufrette\Adapter\AwsS3; class GaufretteFile extends File implements FileInterface { @@ -79,6 +80,11 @@ class GaufretteFile extends File implements FileInterface $this->mimeType = finfo_file($finfo, $this->streamWrapperPrefix.$this->getKey()); finfo_close($finfo); } + } elseif ($this->filesystem->getAdapter() instanceof AwsS3 && !$this->mimeType) { + $metadata = $this->filesystem->getAdapter()->getMetadata($this->getBasename()); + if (isset($metadata['ContentType'])) { + $this->mimeType = $metadata['ContentType']; + } } return $this->mimeType; commit f64018fc329f570fe47652066b15edce79f86021 (from 5904a41f3ff36e5c31753413da7dac507e236439) Merge: 9f7f3fb 5904a41 Author: Jim Schmid <[email protected]> Date: Tue Apr 8 10:15:36 2014 +0200 Merge pull request #100 from ribeiropaulor/bugfix_aws3_adapter bugfix: when using AwsS3 adapter the mimeType was not being set. diff --git a/Controller/AbstractController.php b/Controller/AbstractController.php index fd78592..a551ba8 100644 --- a/Controller/AbstractController.php +++ b/Controller/AbstractController.php @@ -83,7 +83,7 @@ abstract class AbstractController $fileIterator = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($fileBag), \RecursiveIteratorIterator::SELF_FIRST); foreach ($fileIterator as $file) { - if (is_array($file)) { + if (is_array($file) || null === $file) { continue; } diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index 480d8ec..34e707d 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -45,8 +45,11 @@ class OneupUploaderExtension extends Extension foreach ($this->config['mappings'] as $key => $mapping) { $controllers[$key] = $this->processMapping($key, $mapping); $maxsize[$key] = $this->getMaxUploadSize($mapping['max_size']); + + $container->setParameter(sprintf('oneup_uploader.config.%s', $key), $mapping); } + $container->setParameter('oneup_uploader.config', $this->config); $container->setParameter('oneup_uploader.controllers', $controllers); $container->setParameter('oneup_uploader.maxsize', $maxsize); } diff --git a/Tests/Controller/FileBagExtractorTest.php b/Tests/Controller/FileBagExtractorTest.php new file mode 100644 index 0000000..e757ebb --- /dev/null +++ b/Tests/Controller/FileBagExtractorTest.php @@ -0,0 +1,102 @@ +<?php + +namespace Oneup\UploaderBundle\Tests\Controller; + +use Symfony\Component\HttpFoundation\File\UploadedFile; +use Symfony\Component\HttpFoundation\FileBag; + +class FileBagExtractorText extends \PHPUnit_Framework_TestCase +{ + protected $method; + protected $mock; + + public function setUp() + { + $controller = 'Oneup\UploaderBundle\Controller\AbstractController'; + $mock = $this->getMockBuilder($controller) + ->disableOriginalConstructor() + ->getMock() + ; + + $method = new \ReflectionMethod($controller, 'getFiles'); + $method->setAccessible(true); + + $this->method = $method; + $this->mock = $mock; + } + + public function testEmpty() + { + $result = $this->invoke(new FileBag()); + + $this->assertInternalType('array', $result); + $this->assertEmpty($result); + } + + public function testWithNullArrayValue() + { + $bag = new FileBag(array( + array(null) + )); + + $result = $this->invoke($bag); + + $this->assertInternalType('array', $result); + $this->assertEmpty($result); + } + + public function testWithSingleFile() + { + $bag = new FileBag(array( + new UploadedFile(__FILE__, 'name') + )); + + $result = $this->invoke($bag); + + $this->assertInternalType('array', $result); + $this->assertNotEmpty($result); + $this->assertCount(1, $result); + } + + public function testWithMultipleFiles() + { + $bag = new FileBag(array( + new UploadedFile(__FILE__, 'name1'), + new UploadedFile(__FILE__, 'name2'), + new UploadedFile(__FILE__, 'name3') + )); + + $result = $this->invoke($bag); + + $this->assertInternalType('array', $result); + $this->assertNotEmpty($result); + $this->assertCount(3, $result); + } + + public function testWithMultipleFilesContainingNullValues() + { + $bag = new FileBag(array( + // we need to inject an array, + // otherwise the FileBag will type check against + // UploadedFile resulting in an InvalidArgumentException. + array( + new UploadedFile(__FILE__, 'name1'), + null, + new UploadedFile(__FILE__, 'name2'), + null, + new UploadedFile(__FILE__, 'name3') + ) + )); + + $result = $this->invoke($bag); + + $this->assertInternalType('array', $result); + $this->assertNotEmpty($result); + $this->assertCount(3, $result); + } + + protected function invoke(FileBag $bag) + { + return $this->method->invoke($this->mock, $bag); + } +}
0
98b49bf5faf1a775c7552b27e0a86f5af7e22127
1up-lab/OneupUploaderBundle
Switched controller.class parameter according to new config.
commit 98b49bf5faf1a775c7552b27e0a86f5af7e22127 Author: Jim Schmid <[email protected]> Date: Tue Apr 9 20:57:06 2013 +0200 Switched controller.class parameter according to new config. diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index 365063d..3355be5 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -105,11 +105,11 @@ class OneupUploaderExtension extends Extension } $controllerName = sprintf('oneup_uploader.controller.%s', $key); - $controllerType = sprintf('oneup_uploader.controller.%s.class', $mapping['frontend']) + $controllerType = sprintf('oneup_uploader.controller.%s.class', $mapping['frontend']); // create controllers based on mapping $container - ->register($controllerName, $container->getParameter('oneup_uploader.controller.class')) + ->register($controllerName, $controllerType) ->addArgument(new Reference('service_container')) ->addArgument($storageService) diff --git a/Resources/config/uploader.xml b/Resources/config/uploader.xml index 13baac6..ad48473 100644 --- a/Resources/config/uploader.xml +++ b/Resources/config/uploader.xml @@ -7,11 +7,11 @@ <parameter key="oneup_uploader.chunks.manager.class">Oneup\UploaderBundle\Uploader\Chunk\ChunkManager</parameter> <parameter key="oneup_uploader.namer.uniqid.class">Oneup\UploaderBundle\Uploader\Naming\UniqidNamer</parameter> <parameter key="oneup_uploader.routing.loader.class">Oneup\UploaderBundle\Routing\RouteLoader</parameter> - <parameter key="oneup_uploader.controller.class">Oneup\UploaderBundle\Controller\UploaderController</parameter> <parameter key="oneup_uploader.storage.gaufrette.class">Oneup\UploaderBundle\Uploader\Storage\GaufretteStorage</parameter> <parameter key="oneup_uploader.storage.filesystem.class">Oneup\UploaderBundle\Uploader\Storage\FilesystemStorage</parameter> <parameter key="oneup_uploader.orphanage.class">Oneup\UploaderBundle\Uploader\Storage\OrphanageStorage</parameter> <parameter key="oneup_uploader.orphanage.manager.class">Oneup\UploaderBundle\Uploader\Orphanage\OrphanageManager</parameter> + <parameter key="oneup_uploader.controller.fineuploader.class">Oneup\UploaderBundle\Controller\FineUploaderController</parameter> </parameters> <services>
0
8506ef5dc4c680fbdfee1b264a649ced4ca4da48
1up-lab/OneupUploaderBundle
[Documentation] Change console execution path (#314)
commit 8506ef5dc4c680fbdfee1b264a649ced4ca4da48 Author: Łukasz Chruściel <[email protected]> Date: Wed Jan 31 07:09:39 2018 +0100 [Documentation] Change console execution path (#314) diff --git a/Resources/doc/chunked_uploads.md b/Resources/doc/chunked_uploads.md index 2aa007b..cba8760 100644 --- a/Resources/doc/chunked_uploads.md +++ b/Resources/doc/chunked_uploads.md @@ -82,6 +82,6 @@ See the [Use Chunked Uploads behind Load Balancers](load_balancers.md) section i The ChunkManager can be forced to clean up old and orphanaged chunks by using the command provided by the OneupUploaderBundle. - $> php app/console oneup:uploader:clear-chunks + $> php bin/console oneup:uploader:clear-chunks This parameter will clean all chunk files older than the `maxage` value in your configuration.
0
916089d1eecd6ef30ad41203e77b5470bd8cd924
1up-lab/OneupUploaderBundle
Update README.md Added an _Upgrade Notes_ section.
commit 916089d1eecd6ef30ad41203e77b5470bd8cd924 Author: Jim Schmid <[email protected]> Date: Sat Apr 13 13:49:01 2013 +0300 Update README.md Added an _Upgrade Notes_ section. diff --git a/README.md b/README.md index 821a85c..12b3dc7 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,10 @@ The entry point of the documentation can be found in the file `Resources/docs/in [Read the documentation for master](https://github.com/1up-lab/OneupUploaderBundle/blob/master/Resources/doc/index.md) +Upgrade Notes +------------- +Event names [changed](https://github.com/1up-lab/OneupUploaderBundle/commit/f5d5fe4b6f7b9a04ce633acbc9c94a2dd0e0d6be) in Version 0.9.3, update your EventListener accordingly. + License -------
0
3df327868a9863a7102f0601df878fe782440078
1up-lab/OneupUploaderBundle
We have to install our dependencies before we run our test. (important for travis-ci)
commit 3df327868a9863a7102f0601df878fe782440078 Author: Jim Schmid <[email protected]> Date: Mon Mar 11 12:36:31 2013 +0100 We have to install our dependencies before we run our test. (important for travis-ci) diff --git a/.travis.yml b/.travis.yml index bec17da..d231b7e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,4 +2,13 @@ language: php php: - 5.3 - - 5.4 \ No newline at end of file + - 5.4 + +env: + - SYMFONY_VERSION=2.1.* + - SYMFONY_VERSION=2.2.* + - SYMFONY_VERSION=dev-master + +before_script: + - composer require symfony/framework-bundle:${SYMFONY_VERSION} --prefer-source + - composer install --dev --prefer-source \ No newline at end of file
0
4798b107492cfd8c6c483a4a95d86058761975dc
1up-lab/OneupUploaderBundle
Update chunked_uploads.md
commit 4798b107492cfd8c6c483a4a95d86058761975dc Author: mitom <[email protected]> Date: Fri Oct 11 10:37:31 2013 +0200 Update chunked_uploads.md diff --git a/Resources/doc/chunked_uploads.md b/Resources/doc/chunked_uploads.md index 4f5c5e1..7b0dadc 100644 --- a/Resources/doc/chunked_uploads.md +++ b/Resources/doc/chunked_uploads.md @@ -31,11 +31,46 @@ You can configure the `ChunkManager` by using the following configuration parame oneup_uploader: chunks: maxage: 86400 - directory: %kernel.cache_dir%/uploader/chunks + storage: + directory: %kernel.cache_dir%/uploader/chunks ``` You can choose a custom directory to save the chunks temporarily while uploading by changing the parameter `directory`. +Since version 1.0 you can also use a Gaufrette filesystem as the chunk storage. To do this you must first +set up [Gaufrette](gaufrette_storage.md).There are however some additional things to keep in mind. +The configuration for the Gaufrette chunk storage should look as the following: +``` +oneup_uploader: + chunks: + maxage: 86400 + storage: + type: gaufrette + filesystem: gaufrette.gallery_filesystem + prefix: 'chunks' + stream_wrapper: 'gaufrette://gallery/' +``` + +As you can see there are is a new option, ```prefix```. It represents the directory +in *relative* to the filesystem's directory which the chunks are stored in. +Gaufrette won't allow it to be outside of the filesystem. + +> You can only use stream capable filesystems for the chunk storage, at the time of this writing +only the Local filesystem is capable of streaming directly. + +This will give you a better structured directory, +as the chunk's folders and the uploaded files won't mix with each other. +> You can set it to an empty string (```''```), if you don't need it. Otherwise it defaults to ```chunks```. + +The chunks will be read directly from the tmp and appended to the already existing part on the given filesystem, +resulting in only 1 read and 1 write operation. + +You can achieve the biggest improvement if you use the same filesystem as your storage, as if you do so, the assembled +file only has to be moved out of the chunk directory, which on the same filesystem takes almost not time. + +> The load_distribution is forcefully turned on, if you use gaufrette as the chunk storage. + + ## Clean up The ChunkManager can be forced to clean up old and orphanaged chunks by using the command provided by the OneupUploaderBundle.
0
0df4ec461af16dbda9990182cf7596977c4f83d1
1up-lab/OneupUploaderBundle
Inlude the correct namespace for the ValidationException.
commit 0df4ec461af16dbda9990182cf7596977c4f83d1 Author: Jim Schmid <[email protected]> Date: Mon Apr 22 19:14:32 2013 +0200 Inlude the correct namespace for the ValidationException. diff --git a/Controller/AbstractController.php b/Controller/AbstractController.php index 23fb699..06ba7d7 100644 --- a/Controller/AbstractController.php +++ b/Controller/AbstractController.php @@ -15,6 +15,7 @@ use Oneup\UploaderBundle\Event\ValidationEvent; use Oneup\UploaderBundle\Uploader\Storage\StorageInterface; use Oneup\UploaderBundle\Uploader\Response\EmptyResponse; use Oneup\UploaderBundle\Uploader\Response\ResponseInterface; +use Oneup\UploaderBundle\Uploader\Exception\ValidationException; abstract class AbstractController {
0
283c3ae9f278393e76d242c786107d25a2f78a52
1up-lab/OneupUploaderBundle
Made the whole Orphenage-thingy work.
commit 283c3ae9f278393e76d242c786107d25a2f78a52 Author: Jim Schmid <[email protected]> Date: Wed Mar 13 16:45:07 2013 +0100 Made the whole Orphenage-thingy work. diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index e9e67b3..b07d7a2 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -78,6 +78,29 @@ class OneupUploaderExtension extends Extension protected function registerServicesPerMap(ContainerBuilder $container, $type, $mapping) { + if($mapping['use_orphanage']) + { + // this mapping want to use the orphanage, so create a typed one + $container + ->register(sprintf('oneup_uploader.orphanage.%s', $type), $container->getParameter('oneup_uploader.orphanage.class')) + + ->addArgument(new Reference('session')) + ->addArgument(new Reference($mapping['storage'])) + ->addArgument($container->getParameter('oneup_uploader.orphanage')) + ->addArgument($type) + ; + + $container + ->getDefinition('oneup_uploader.orphanage_manager') + + // add this service to the orphanage manager + ->addMethodCall('addImplementation', array( + $type, + new Reference(sprintf('oneup_uploader.orphanage.%s', $type)) + )) + ; + } + // create controllers based on mapping $container ->register(sprintf('oneup_uploader.controller.%s', $type), $container->getParameter('oneup_uploader.controller.class')) diff --git a/EventListener/OrphanageListener.php b/EventListener/OrphanageListener.php index 15bd7c9..f830b39 100644 --- a/EventListener/OrphanageListener.php +++ b/EventListener/OrphanageListener.php @@ -7,15 +7,15 @@ use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Oneup\UploaderBundle\Event\PostUploadEvent; use Oneup\UploaderBundle\UploadEvents; -use Oneup\UploaderBundle\Uploader\Orphanage\OrphanageInterface; +use Oneup\UploaderBundle\Uploader\Orphanage\OrphanageManagerInterface; class OrphanageListener implements EventSubscriberInterface { - protected $orphanage; + protected $manager; - public function __construct(OrphanageInterface $orphanage) + public function __construct(OrphanageManagerInterface $manager) { - $this->orphanage = $orphanage; + $this->manager = $manager; } public function add(PostUploadEvent $event) @@ -23,11 +23,12 @@ class OrphanageListener implements EventSubscriberInterface $options = $event->getOptions(); $request = $event->getRequest(); $file = $event->getFile(); + $type = $event->getType(); if(!array_key_exists('use_orphanage', $options) || !$options['use_orphanage']) return; - $this->orphanage->addFile($file, $options['file_name']); + $this->manager->get($type)->addFile($file, $options['file_name']); } public static function getSubscribedEvents() diff --git a/Resources/config/uploader.xml b/Resources/config/uploader.xml index f7efd15..04ce1ea 100644 --- a/Resources/config/uploader.xml +++ b/Resources/config/uploader.xml @@ -15,17 +15,13 @@ </parameters> <services> - <service id="oneup_uploader.chunks.manager" class="%oneup_uploader.chunks.manager.class%"> + <service id="oneup_uploader.chunks_manager" class="%oneup_uploader.chunks.manager.class%"> <argument>%oneup_uploader.chunks%</argument> </service> <!-- orphanage --> - <service id="oneup_uploader.orphanage.manager" class="%oneup_uploader.orphanage.manager.class%"> - <argument>%oneup_uploader.orphanage%</argument> - </service> - - <service id="oneup_uploader.orphanage" class="%oneup_uploader.orphanage.class%"> - <argument type="service" id="session" /> + <service id="oneup_uploader.orphanage_manager" class="%oneup_uploader.orphanage.manager.class%"> + <argument type="service" id="service_container" /> <argument>%oneup_uploader.orphanage%</argument> </service> @@ -39,7 +35,7 @@ <!-- events --> <service id="oneup_uploader.listener.orphanage" class="%oneup_uploader.listener.session.class%"> - <argument type="service" id="oneup_uploader.orphanage" /> + <argument type="service" id="oneup_uploader.orphanage_manager" /> <tag name="kernel.event_subscriber" /> </service> diff --git a/Uploader/Orphanage/Orphanage.php b/Uploader/Orphanage/Orphanage.php index 4a7971d..93b22e6 100644 --- a/Uploader/Orphanage/Orphanage.php +++ b/Uploader/Orphanage/Orphanage.php @@ -2,20 +2,27 @@ namespace Oneup\UploaderBundle\Uploader\Orphanage; - +use Symfony\Component\Finder\Finder; +use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\HttpFoundation\File\File; use Symfony\Component\HttpFoundation\Session\SessionInterface; +use Oneup\UploaderBundle\Uploader\Storage\StorageInterface; use Oneup\UploaderBundle\Uploader\Orphanage\OrphanageInterface; class Orphanage implements OrphanageInterface { protected $session; + protected $storage; + protected $namer; protected $config; + protected $type; - public function __construct(SessionInterface $session, $config) + public function __construct(SessionInterface $session, StorageInterface $storage, $config, $type) { $this->session = $session; - $this->config = $config; + $this->storage = $storage; + $this->config = $config; + $this->type = $type; } public function addFile(File $file, $name) @@ -27,12 +34,40 @@ class Orphanage implements OrphanageInterface return $file->move($this->getPath(), $name); } - public function getFiles() + public function uploadFiles($keep = false) { + $system = new Filesystem(); + $finder = new Finder(); + + if(!$system->exists($this->getPath())) + return array(); + + $finder->in($this->getPathRelativeToSession())->files(); + $uploaded = array(); + + foreach($finder as $file) + { + $uploaded[] = $this->storage->upload($file); + + if(!$keep) + { + $system->remove($file); + } + } + + return $uploaded; } protected function getPath() + { + $id = $this->session->getId(); + $path = sprintf('%s/%s/%s', $this->config['directory'], $id, $this->type); + + return $path; + } + + protected function getPathRelativeToSession() { $id = $this->session->getId(); $path = sprintf('%s/%s', $this->config['directory'], $id); diff --git a/Uploader/Orphanage/OrphanageManager.php b/Uploader/Orphanage/OrphanageManager.php index 9657d7a..e993938 100644 --- a/Uploader/Orphanage/OrphanageManager.php +++ b/Uploader/Orphanage/OrphanageManager.php @@ -9,9 +9,13 @@ use Oneup\UploaderBundle\Uploader\Orphanage\OrphanageManagerInterface; class OrphanageManager implements OrphanageManagerInterface { - public function __construct($configuration) + protected $orphanages; + + public function __construct($container, $configuration) { + $this->container = $container; $this->configuration = $configuration; + $this->orphanages = array(); } public function warmup() @@ -42,4 +46,22 @@ class OrphanageManager implements OrphanageManagerInterface $system->remove($file); } } + + public function get($type) + { + return $this->getImplementation($type); + } + + public function getImplementation($type) + { + if(!array_key_exists($type, $this->orphanages)) + throw new \InvalidArgumentException(sprintf('No Orphanage implementation of type "%s" found.', $type)); + + return $this->orphanages[$type]; + } + + public function addImplementation($type, OrphanageInterface $orphanage) + { + $this->orphanages[$type] = $orphanage; + } } \ No newline at end of file diff --git a/Uploader/Orphanage/OrphanageManagerInterface.php b/Uploader/Orphanage/OrphanageManagerInterface.php index 52c3807..01bf0dc 100644 --- a/Uploader/Orphanage/OrphanageManagerInterface.php +++ b/Uploader/Orphanage/OrphanageManagerInterface.php @@ -2,8 +2,12 @@ namespace Oneup\UploaderBundle\Uploader\Orphanage; +use Oneup\UploaderBundle\Uploader\Orphanage\OrphanageInterface; + interface OrphanageManagerInterface { public function warmup(); public function clear(); + public function getImplementation($type); + public function addImplementation($type, OrphanageInterface $orphanage); } \ No newline at end of file diff --git a/Uploader/Storage/GaufretteStorage.php b/Uploader/Storage/GaufretteStorage.php index 4268814..77464be 100644 --- a/Uploader/Storage/GaufretteStorage.php +++ b/Uploader/Storage/GaufretteStorage.php @@ -2,7 +2,7 @@ namespace Oneup\UploaderBundle\Uploader\Storage; -use Symfony\Component\HttpFoundation\File\File; +use Symfony\Component\Finder\SplFileInfo as File; use Gaufrette\Stream\Local as LocalStream; use Gaufrette\StreamMode; use Gaufrette\Filesystem; @@ -17,10 +17,11 @@ class GaufretteStorage implements StorageInterface $this->filesystem = $filesystem; } - public function upload(File $file, $name) + public function upload(File $file, $name = null) { $path = $file->getPathname(); - + $name = is_null($name) ? $file->getRelativePathname() : $name; + $src = new LocalStream($path); $dst = $this->filesystem->createStream($name); @@ -28,7 +29,7 @@ class GaufretteStorage implements StorageInterface // because the stream-mode is not able to create // subdirectories. if(!$this->filesystem->has($name)) - $this->filesystem->createFile($name); + $this->filesystem->write($name, '', true); $src->open(new StreamMode('rb+')); $dst->open(new StreamMode('ab+')); diff --git a/Uploader/Storage/StorageInterface.php b/Uploader/Storage/StorageInterface.php index 1e4a287..0e9b830 100644 --- a/Uploader/Storage/StorageInterface.php +++ b/Uploader/Storage/StorageInterface.php @@ -2,10 +2,10 @@ namespace Oneup\UploaderBundle\Uploader\Storage; -use Symfony\Component\HttpFoundation\File\File; +use Symfony\Component\Finder\SplFileInfo as File; interface StorageInterface { - public function upload(File $file, $name); + public function upload(\SplFileInfo $file, $name); public function remove(File $file); } \ No newline at end of file
0
36de4a72e1cbb4e29d11b2046becdea5664a9ea9
1up-lab/OneupUploaderBundle
Merge pull request #165 from Gladhon/master Add Errorhandling to Dropzone
commit 36de4a72e1cbb4e29d11b2046becdea5664a9ea9 (from 98a34307e1c291e92424ecdfc97193e572449e9e) Merge: 98a3430 1fd15f7 Author: Jim Schmid <[email protected]> Date: Fri Feb 20 18:20:39 2015 +0100 Merge pull request #165 from Gladhon/master Add Errorhandling to Dropzone diff --git a/Controller/DropzoneController.php b/Controller/DropzoneController.php index 0c8a5b0..2121f32 100644 --- a/Controller/DropzoneController.php +++ b/Controller/DropzoneController.php @@ -20,6 +20,11 @@ class DropzoneController extends AbstractController $this->handleUpload($file, $response, $request); } catch (UploadException $e) { $this->errorHandler->addException($response, $e); + $translator = $this->container->get('translator'); + $message = $translator->trans($e->getMessage(), array(), 'OneupUploaderBundle'); + $response = $this->createSupportedJsonResponse(array('error'=>$message )); + $response->setStatusCode(400); + return $response; } }
0
7c36e982eeee3918b84ca13dd53cebc3fdf65602
1up-lab/OneupUploaderBundle
Removed first title on testing.md.
commit 7c36e982eeee3918b84ca13dd53cebc3fdf65602 Author: Jim Schmid <[email protected]> Date: Tue Apr 9 09:11:57 2013 +0200 Removed first title on testing.md. diff --git a/Resources/doc/testing.md b/Resources/doc/testing.md index 8db8597..7da4cb2 100644 --- a/Resources/doc/testing.md +++ b/Resources/doc/testing.md @@ -1,8 +1,6 @@ Testing the Bundle ================== -## Install the Environment - In order to run the UnitTests of this bundle, clone it first $> git clone git://github.com/1up-lab/OneupUploaderBundle.git
0
07e294cb11a6287ece278887400af2f1547fa511
1up-lab/OneupUploaderBundle
Removed max version constraint for symfony/finder.
commit 07e294cb11a6287ece278887400af2f1547fa511 Author: Jim Schmid <[email protected]> Date: Mon Oct 7 12:28:30 2013 +0200 Removed max version constraint for symfony/finder. diff --git a/composer.json b/composer.json index 37e7667..b4a4d15 100644 --- a/composer.json +++ b/composer.json @@ -16,7 +16,7 @@ "require": { "symfony/framework-bundle": "2.*", - "symfony/finder": ">=2.2.0,<2.4-dev" + "symfony/finder": ">=2.2.0" }, "require-dev": {
0
c4421355b4916617d4f7b570f2c3cb7c5f887160
1up-lab/OneupUploaderBundle
Removed an incorrect downgrade of max_size. This fixes the following situation: You are using chunked uploads. The total size of the file is 12MB, whereas `min(upload_max_size, post_max_size)` is limited to 8MB. The The downgrading is still implemented. If you wish to gracefully downgrade max_size, set the configuration value to -1. This addresses #35.
commit c4421355b4916617d4f7b570f2c3cb7c5f887160 Author: Jim Schmid <[email protected]> Date: Thu Jul 25 13:13:20 2013 +0200 Removed an incorrect downgrade of max_size. This fixes the following situation: You are using chunked uploads. The total size of the file is 12MB, whereas `min(upload_max_size, post_max_size)` is limited to 8MB. The The downgrading is still implemented. If you wish to gracefully downgrade max_size, set the configuration value to -1. This addresses #35. diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index cbf59dd..8543d7d 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -72,7 +72,10 @@ class Configuration implements ConfigurationInterface ->prototype('scalar')->end() ->end() ->scalarNode('error_handler')->defaultValue('oneup_uploader.error_handler.noop')->end() - ->scalarNode('max_size')->defaultValue(\PHP_INT_MAX)->end() + ->scalarNode('max_size') + ->defaultValue(\PHP_INT_MAX) + ->info('Set max_size to -1 for gracefully downgrade this number to the systems max upload size.') + ->end() ->booleanNode('use_orphanage')->defaultFalse()->end() ->booleanNode('enable_progress')->defaultFalse()->end() ->booleanNode('enable_cancelation')->defaultFalse()->end() diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index a7cdbba..4e9b72a 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -46,7 +46,10 @@ class OneupUploaderExtension extends Extension // handle mappings foreach ($config['mappings'] as $key => $mapping) { - $mapping['max_size'] = $this->getMaxUploadSize($mapping['max_size']); + $mapping['max_size'] = $mapping['max_size'] < 0 ? + $this->getMaxUploadSize($mapping['max_size']) : + $mapping['max_size'] + ; // create the storage service according to the configuration $storageService = null; diff --git a/Resources/doc/configuration_reference.md b/Resources/doc/configuration_reference.md index 52edb2d..7273963 100644 --- a/Resources/doc/configuration_reference.md +++ b/Resources/doc/configuration_reference.md @@ -8,6 +8,7 @@ oneup_uploader: chunks: maxage: 604800 directory: ~ + load_distribution: true orphanage: maxage: 604800 directory: ~ @@ -29,10 +30,13 @@ oneup_uploader: disallowed_extensions: [] allowed_mimetypes: [] disallowed_mimetypes: [] - error_handler: oneup_uploader.error_handler.noop + error_handler: oneup_uploader.error_handler.noop + + # Set max_size to -1 for gracefully downgrade this number to the systems max upload size. max_size: 9223372036854775807 use_orphanage: false enable_progress: false enable_cancelation: false namer: oneup_uploader.namer.uniqid + ``` diff --git a/Tests/DependencyInjection/OneupUploaderExtensionTest.php b/Tests/DependencyInjection/OneupUploaderExtensionTest.php index f68e764..1b09fbf 100644 --- a/Tests/DependencyInjection/OneupUploaderExtensionTest.php +++ b/Tests/DependencyInjection/OneupUploaderExtensionTest.php @@ -4,8 +4,59 @@ namespace Oneup\UploaderBundle\Tests\DependencyInjection; class OneupUploaderExtensionTest extends \PHPUnit_Framework_TestCase { - public function testDummyForSetup() + public function testValueToByteTransformer() { - $this->assertTrue(true); + $mock = $this->getMockBuilder('Oneup\UploaderBundle\DependencyInjection\OneupUploaderExtension') + ->disableOriginalConstructor() + ->getMock() + ; + + $method = new \ReflectionMethod( + 'Oneup\UploaderBundle\DependencyInjection\OneupUploaderExtension', + 'getValueInBytes' + ); + $method->setAccessible(true); + + $this->assertEquals(15, $method->invoke($mock, ' 15')); + $this->assertEquals(15, $method->invoke($mock, '15 ')); + + $this->assertEquals(1024, $method->invoke($mock, '1K')); + $this->assertEquals(2048, $method->invoke($mock, '2K')); + $this->assertEquals(1048576, $method->invoke($mock, '1M')); + $this->assertEquals(2097152, $method->invoke($mock, '2M')); + $this->assertEquals(1073741824, $method->invoke($mock, '1G')); + $this->assertEquals(2147483648, $method->invoke($mock, '2G')); + } + + public function testGetMaxUploadSize() + { + $mock = $this->getMockBuilder('Oneup\UploaderBundle\DependencyInjection\OneupUploaderExtension') + ->disableOriginalConstructor() + ->getMock() + ; + + $getMaxUploadSize = new \ReflectionMethod( + 'Oneup\UploaderBundle\DependencyInjection\OneupUploaderExtension', + 'getMaxUploadSize' + ); + + $getValueInBytes = new \ReflectionMethod( + 'Oneup\UploaderBundle\DependencyInjection\OneupUploaderExtension', + 'getValueInBytes' + ); + + $getMaxUploadSize->setAccessible(true); + $getValueInBytes->setAccessible(true); + + $store = array( + $getValueInBytes->invoke($mock, ini_get('upload_max_filesize')), + $getValueInBytes->invoke($mock, ini_get('post_max_size')) + ); + + $min = min($store); + + $this->assertEquals(0, $getMaxUploadSize->invoke($mock, 0)); + $this->assertEquals(min(10, $min), $getMaxUploadSize->invoke($mock, min(10, $min))); + $this->assertEquals(min(\PHP_INT_MAX, $min), $getMaxUploadSize->invoke($mock, min(\PHP_INT_MAX, $min))); } }
0
b17bee4fbd2d39a603218f2959bb0389e7828e6a
1up-lab/OneupUploaderBundle
Fix configuration for storage service creation
commit b17bee4fbd2d39a603218f2959bb0389e7828e6a Author: PaulM <[email protected]> Date: Tue Oct 15 11:11:53 2013 +0200 Fix configuration for storage service creation diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index c017bdc..f6720a6 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -169,7 +169,7 @@ class OneupUploaderExtension extends Extension // if a service is given, return a reference to this service // this allows a user to overwrite the storage layer if needed if (!is_null($config['service'])) { - $storageService = new Reference($config['storage']['service']); + $storageService = new Reference($config['service']); } else { // no service was given, so we create one $storageName = sprintf('oneup_uploader.storage.%s', $key);
0
15a45904ca8452fb281020a49c732f9391031e04
1up-lab/OneupUploaderBundle
Normalize stream wrapper path. This way it is not important to remember appending a / to the end of the stream_wrapper string.
commit 15a45904ca8452fb281020a49c732f9391031e04 Author: Jim Schmid <[email protected]> Date: Mon Oct 14 20:05:14 2013 +0200 Normalize stream wrapper path. This way it is not important to remember appending a / to the end of the stream_wrapper string. diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index b25c844..c017bdc 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -229,6 +229,8 @@ class OneupUploaderExtension extends Extension if(strlen($filesystem) <= 0) throw new ServiceNotFoundException('Empty service name'); + $streamWrapper = $this->normalizeStreamWrapper($streamWrapper); + $this->container ->register($key, $class) ->addArgument(new Reference($filesystem)) @@ -266,4 +268,13 @@ class OneupUploaderExtension extends Extension { return rtrim($input, '/'); } + + protected function normalizeStreamWrapper($input) + { + if (is_null($input)) { + return null; + } + + return rtrim($input, '/') . '/'; + } } diff --git a/Tests/DependencyInjection/OneupUploaderExtensionTest.php b/Tests/DependencyInjection/OneupUploaderExtensionTest.php index 1b09fbf..85ac094 100644 --- a/Tests/DependencyInjection/OneupUploaderExtensionTest.php +++ b/Tests/DependencyInjection/OneupUploaderExtensionTest.php @@ -28,6 +28,28 @@ class OneupUploaderExtensionTest extends \PHPUnit_Framework_TestCase $this->assertEquals(2147483648, $method->invoke($mock, '2G')); } + public function testNormalizationOfStreamWrapper() + { + $mock = $this->getMockBuilder('Oneup\UploaderBundle\DependencyInjection\OneupUploaderExtension') + ->disableOriginalConstructor() + ->getMock() + ; + + $method = new \ReflectionMethod( + 'Oneup\UploaderBundle\DependencyInjection\OneupUploaderExtension', + 'normalizeStreamWrapper' + ); + $method->setAccessible(true); + + $output1 = $method->invoke($mock, 'gaufrette://gallery'); + $output2 = $method->invoke($mock, 'gaufrette://gallery/'); + $output3 = $method->invoke($mock, null); + + $this->assertEquals('gaufrette://gallery/', $output1); + $this->assertEquals('gaufrette://gallery/', $output2); + $this->assertNull($output3); + } + public function testGetMaxUploadSize() { $mock = $this->getMockBuilder('Oneup\UploaderBundle\DependencyInjection\OneupUploaderExtension')
0
e8e37b7b819eaf3ef2f5f95b9ff37a6f96f2bb8c
1up-lab/OneupUploaderBundle
Removed unused line of code.
commit e8e37b7b819eaf3ef2f5f95b9ff37a6f96f2bb8c Author: Jim Schmid <[email protected]> Date: Fri Apr 12 12:12:56 2013 +0200 Removed unused line of code. diff --git a/Uploader/Storage/FilesystemStorage.php b/Uploader/Storage/FilesystemStorage.php index 2cd35ea..4d52bb9 100644 --- a/Uploader/Storage/FilesystemStorage.php +++ b/Uploader/Storage/FilesystemStorage.php @@ -20,7 +20,6 @@ class FilesystemStorage implements StorageInterface { $filesystem = new Filesystem(); - $name = is_null($name) ? $file->getRelativePathname() : $name; $path = is_null($path) ? $name : sprintf('%s/%s', $path, $name); $path = sprintf('%s/%s', $this->directory, $path);
0
a89695ba61b8a565457b04313679149d2aad1ecc
1up-lab/OneupUploaderBundle
Fixed wrong commented lines.
commit a89695ba61b8a565457b04313679149d2aad1ecc Author: Jim Schmid <[email protected]> Date: Thu Apr 18 18:42:35 2013 +0200 Fixed wrong commented lines. diff --git a/Controller/AbstractController.php b/Controller/AbstractController.php index c53e574..07836d0 100644 --- a/Controller/AbstractController.php +++ b/Controller/AbstractController.php @@ -50,12 +50,13 @@ abstract class AbstractController { $dispatcher = $this->container->get('event_dispatcher'); + // dispatch post upload event $postUploadEvent = new PostUploadEvent($uploaded, $response, $request, $this->type, $this->config); $dispatcher->dispatch(UploadEvents::POST_UPLOAD, $postUploadEvent); if(!$this->config['use_orphanage']) { - // dispatch post upload event + // dispatch post persist event $postPersistEvent = new PostPersistEvent($uploaded, $response, $request, $this->type, $this->config); $dispatcher->dispatch(UploadEvents::POST_PERSIST, $postPersistEvent); }
0
75b9de7220ee7b8641601a20bffff754eb93cab4
1up-lab/OneupUploaderBundle
Exception tweaks. ValidationException is now extending Symfonys UploadException and will be passed through. There is now a new field for adding custom error messages.
commit 75b9de7220ee7b8641601a20bffff754eb93cab4 Author: Jim Schmid <[email protected]> Date: Sun Jul 14 23:48:05 2013 +0200 Exception tweaks. ValidationException is now extending Symfonys UploadException and will be passed through. There is now a new field for adding custom error messages. diff --git a/Controller/AbstractController.php b/Controller/AbstractController.php index 4adb51e..865517d 100644 --- a/Controller/AbstractController.php +++ b/Controller/AbstractController.php @@ -4,7 +4,6 @@ namespace Oneup\UploaderBundle\Controller; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\DependencyInjection\ContainerInterface; -use Symfony\Component\HttpFoundation\File\Exception\UploadException; use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\HttpFoundation\Request; @@ -15,7 +14,6 @@ use Oneup\UploaderBundle\Event\PostUploadEvent; use Oneup\UploaderBundle\Event\ValidationEvent; use Oneup\UploaderBundle\Uploader\Storage\StorageInterface; use Oneup\UploaderBundle\Uploader\Response\ResponseInterface; -use Oneup\UploaderBundle\Uploader\Exception\ValidationException; use Oneup\UploaderBundle\Uploader\ErrorHandler\ErrorHandlerInterface; abstract class AbstractController @@ -144,11 +142,6 @@ abstract class AbstractController $dispatcher = $this->container->get('event_dispatcher'); $event = new ValidationEvent($file, $this->config, $this->type); - try { - $dispatcher->dispatch(UploadEvents::VALIDATION, $event); - } catch (ValidationException $exception) { - // pass the exception one level up - throw new UploadException($exception->getMessage()); - } + $dispatcher->dispatch(UploadEvents::VALIDATION, $event); } } diff --git a/Controller/BlueimpController.php b/Controller/BlueimpController.php index 02b09f2..c0842a8 100644 --- a/Controller/BlueimpController.php +++ b/Controller/BlueimpController.php @@ -19,7 +19,7 @@ class BlueimpController extends AbstractChunkedController $chunked = !is_null($request->headers->get('content-range')); - foreach ((array)$files as $file) { + foreach ((array) $files as $file) { try { $chunked ? $this->handleChunkedUpload($file, $response, $request) : diff --git a/Controller/FineUploaderController.php b/Controller/FineUploaderController.php index 0c862a3..a9dc1b1 100644 --- a/Controller/FineUploaderController.php +++ b/Controller/FineUploaderController.php @@ -30,7 +30,7 @@ class FineUploaderController extends AbstractChunkedController } catch (UploadException $e) { $response->setSuccess(false); $response->setError($translator->trans($e->getMessage(), array(), 'OneupUploaderBundle')); - + $this->errorHandler->addException($response, $e); // an error happended, return this error message. diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index b83a59a..108394c 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -116,7 +116,7 @@ class OneupUploaderExtension extends Extension if(empty($controllerName) || empty($controllerType)) throw new ServiceNotFoundException('Empty controller class or name. If you really want to use a custom frontend implementation, be sure to provide a class and a name.'); } - + $errorHandler = new Reference($mapping['error_handler']); // create controllers based on mapping @@ -133,8 +133,8 @@ class OneupUploaderExtension extends Extension ->setScope('request') ; - if($mapping['enable_progress'] || $mapping['enable_cancelation']) { - if(strnatcmp(phpversion(), '5.4.0') < 0) { + if ($mapping['enable_progress'] || $mapping['enable_cancelation']) { + if (strnatcmp(phpversion(), '5.4.0') < 0) { throw new InvalidArgumentException('You need to run PHP version 5.4.0 or above to use the progress/cancelation feature.'); } } diff --git a/Tests/Controller/BlueimpTest.php b/Tests/Controller/BlueimpTest.php index e6d4b36..44e07bd 100644 --- a/Tests/Controller/BlueimpTest.php +++ b/Tests/Controller/BlueimpTest.php @@ -71,7 +71,7 @@ class BlueimpTest extends AbstractUploadTest $this->assertEquals($uploadCount, count($this->getUploadedFiles())); $this->assertEquals(1, $preValidation); } - + protected function getConfigKey() { return 'blueimp'; diff --git a/Tests/Controller/BlueimpValidationTest.php b/Tests/Controller/BlueimpValidationTest.php index bbaa728..dc90c38 100644 --- a/Tests/Controller/BlueimpValidationTest.php +++ b/Tests/Controller/BlueimpValidationTest.php @@ -110,7 +110,7 @@ class BlueimpValidationTest extends AbstractValidationTest $this->assertEquals($response->headers->get('Content-Type'), 'application/json'); $this->assertCount(0, $this->getUploadedFiles()); } - + protected function getConfigKey() { return 'blueimp_validation'; diff --git a/Uploader/ErrorHandler/BlueimpErrorHandler.php b/Uploader/ErrorHandler/BlueimpErrorHandler.php index 5187f90..299dae1 100644 --- a/Uploader/ErrorHandler/BlueimpErrorHandler.php +++ b/Uploader/ErrorHandler/BlueimpErrorHandler.php @@ -10,6 +10,12 @@ class BlueimpErrorHandler implements ErrorHandlerInterface { public function addException(ResponseInterface $response, UploadException $exception) { - $response->addToOffset($exception->getMessage(), 'files'); + if ($exception instanceof ValidationException) { + $message = $exception->getErrorMessage(); + } else { + $message = $exception->getMessage(); + } + + $response->addToOffset(array('error' => $message), 'files'); } } diff --git a/Uploader/ErrorHandler/ErrorHandlerInterface.php b/Uploader/ErrorHandler/ErrorHandlerInterface.php index 9b7a50a..a2614a1 100644 --- a/Uploader/ErrorHandler/ErrorHandlerInterface.php +++ b/Uploader/ErrorHandler/ErrorHandlerInterface.php @@ -1,5 +1,5 @@ <?php - + namespace Oneup\UploaderBundle\Uploader\ErrorHandler; use Symfony\Component\HttpFoundation\File\Exception\UploadException; diff --git a/Uploader/Exception/ValidationException.php b/Uploader/Exception/ValidationException.php index 6d632f1..47b75c0 100644 --- a/Uploader/Exception/ValidationException.php +++ b/Uploader/Exception/ValidationException.php @@ -2,7 +2,26 @@ namespace Oneup\UploaderBundle\Uploader\Exception; -class ValidationException extends \DomainException +use Symfony\Component\HttpFoundation\File\Exception\UploadException; + +class ValidationException extends UploadException { + protected $errorMessage; + + public function setErrorMessage($message) + { + $this->errorMessage = $message; + + return $this; + } + + public function getErrorMessage() + { + // if no error message is set, return the exception message + if (!$this->errorMessage) { + return $this->getMessage(); + } + return $this->errorMessage; + } } diff --git a/Uploader/Response/AbstractResponse.php b/Uploader/Response/AbstractResponse.php index 561c7b7..913b000 100644 --- a/Uploader/Response/AbstractResponse.php +++ b/Uploader/Response/AbstractResponse.php @@ -32,4 +32,13 @@ abstract class AbstractResponse implements \ArrayAccess, ResponseInterface { return isset($this->data[$offset]) ? $this->data[$offset] : null; } + + public function addToOffset($offset, array $value) + { + if (!array_key_exists($offset, $this->data)) { + $this->data[$offset] = array(); + } + + $this->data[$offset] += $value; + } }
0
d7802d5ac23bb115ca263ede9dece80fbb14f8f3
1up-lab/OneupUploaderBundle
BlueimpController now uses the correct array key when reading files from FileBag.
commit d7802d5ac23bb115ca263ede9dece80fbb14f8f3 Author: Jim Schmid <[email protected]> Date: Sun Jul 14 23:17:53 2013 +0200 BlueimpController now uses the correct array key when reading files from FileBag. diff --git a/Controller/BlueimpController.php b/Controller/BlueimpController.php index 7ab6fe0..02b09f2 100644 --- a/Controller/BlueimpController.php +++ b/Controller/BlueimpController.php @@ -15,13 +15,11 @@ class BlueimpController extends AbstractChunkedController { $request = $this->container->get('request'); $response = new EmptyResponse(); - $files = $request->files; + $files = $request->files->get('files'); $chunked = !is_null($request->headers->get('content-range')); - foreach ($files as $file) { - $file = $file[0]; - + foreach ((array)$files as $file) { try { $chunked ? $this->handleChunkedUpload($file, $response, $request) : diff --git a/Tests/Controller/BlueimpTest.php b/Tests/Controller/BlueimpTest.php index 0d515b5..e6d4b36 100644 --- a/Tests/Controller/BlueimpTest.php +++ b/Tests/Controller/BlueimpTest.php @@ -4,9 +4,74 @@ namespace Oneup\UploaderBundle\Tests\Controller; use Symfony\Component\HttpFoundation\File\UploadedFile; use Oneup\UploaderBundle\Tests\Controller\AbstractUploadTest; +use Oneup\UploaderBundle\UploadEvents; +use Oneup\UploaderBundle\Event\PreUploadEvent; +use Oneup\UploaderBundle\Event\PostUploadEvent; class BlueimpTest extends AbstractUploadTest { + public function testSingleUpload() + { + // assemble a request + $client = $this->client; + $endpoint = $this->helper->endpoint($this->getConfigKey()); + + $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getRequestFile()); + $response = $client->getResponse(); + + $this->assertTrue($response->isSuccessful()); + $this->assertEquals($response->headers->get('Content-Type'), 'application/json'); + $this->assertCount(1, $this->getUploadedFiles()); + + foreach ($this->getUploadedFiles() as $file) { + $this->assertTrue($file->isFile()); + $this->assertTrue($file->isReadable()); + $this->assertEquals(128, $file->getSize()); + } + } + + public function testEvents() + { + $client = $this->client; + $endpoint = $this->helper->endpoint($this->getConfigKey()); + $dispatcher = $client->getContainer()->get('event_dispatcher'); + + // event data + $me = $this; + $uploadCount = 0; + $preValidation = 1; + + $dispatcher->addListener(UploadEvents::PRE_UPLOAD, function(PreUploadEvent $event) use (&$uploadCount, &$me, &$preValidation) { + $preValidation -= 2; + + $file = $event->getFile(); + $request = $event->getRequest(); + + // add a new key to the attribute list + $request->attributes->set('grumpy', 'cat'); + + $me->assertInstanceOf('Symfony\Component\HttpFoundation\File\UploadedFile', $file); + }); + + $dispatcher->addListener(UploadEvents::POST_UPLOAD, function(PostUploadEvent $event) use (&$uploadCount, &$me, &$preValidation) { + ++ $uploadCount; + $preValidation *= -1; + + $file = $event->getFile(); + $request = $event->getRequest(); + + $me->assertInstanceOf('Symfony\Component\HttpFoundation\File\File', $file); + $me->assertEquals(128, $file->getSize()); + $me->assertEquals('cat', $request->get('grumpy')); + }); + + $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getRequestFile()); + + $this->assertCount(1, $this->getUploadedFiles()); + $this->assertEquals($uploadCount, count($this->getUploadedFiles())); + $this->assertEquals(1, $preValidation); + } + protected function getConfigKey() { return 'blueimp'; @@ -19,11 +84,11 @@ class BlueimpTest extends AbstractUploadTest protected function getRequestFile() { - return array(new UploadedFile( + return array('files' => array(new UploadedFile( $this->createTempFile(128), 'cat.txt', 'text/plain', 128 - )); + ))); } } diff --git a/Tests/Controller/BlueimpValidationTest.php b/Tests/Controller/BlueimpValidationTest.php index e2cd6cd..bbaa728 100644 --- a/Tests/Controller/BlueimpValidationTest.php +++ b/Tests/Controller/BlueimpValidationTest.php @@ -4,9 +4,113 @@ namespace Oneup\UploaderBundle\Tests\Controller; use Symfony\Component\HttpFoundation\File\UploadedFile; use Oneup\UploaderBundle\Tests\Controller\AbstractValidationTest; +use Oneup\UploaderBundle\Event\ValidationEvent; +use Oneup\UploaderBundle\UploadEvents; class BlueimpValidationTest extends AbstractValidationTest { + public function testAgainstMaxSize() + { + // assemble a request + $client = $this->client; + $endpoint = $this->helper->endpoint($this->getConfigKey()); + + $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getOversizedFile()); + $response = $client->getResponse(); + + //$this->assertTrue($response->isNotSuccessful()); + $this->assertEquals($response->headers->get('Content-Type'), 'application/json'); + $this->assertCount(0, $this->getUploadedFiles()); + } + + public function testAgainstCorrectExtension() + { + // assemble a request + $client = $this->client; + $endpoint = $this->helper->endpoint($this->getConfigKey()); + + $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getFileWithCorrectExtension()); + $response = $client->getResponse(); + + $this->assertTrue($response->isSuccessful()); + $this->assertEquals($response->headers->get('Content-Type'), 'application/json'); + $this->assertCount(1, $this->getUploadedFiles()); + + foreach ($this->getUploadedFiles() as $file) { + $this->assertTrue($file->isFile()); + $this->assertTrue($file->isReadable()); + $this->assertEquals(128, $file->getSize()); + } + } + + public function testEvents() + { + $client = $this->client; + $endpoint = $this->helper->endpoint($this->getConfigKey()); + $dispatcher = $client->getContainer()->get('event_dispatcher'); + + // event data + $validationCount = 0; + + $dispatcher->addListener(UploadEvents::VALIDATION, function(ValidationEvent $event) use (&$validationCount) { + ++ $validationCount; + }); + + $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getFileWithCorrectExtension()); + + $this->assertEquals(1, $validationCount); + } + + public function testAgainstIncorrectExtension() + { + // assemble a request + $client = $this->client; + $endpoint = $this->helper->endpoint($this->getConfigKey()); + + $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getFileWithIncorrectExtension()); + $response = $client->getResponse(); + + //$this->assertTrue($response->isNotSuccessful()); + $this->assertEquals($response->headers->get('Content-Type'), 'application/json'); + $this->assertCount(0, $this->getUploadedFiles()); + } + + public function testAgainstCorrectMimeType() + { + // assemble a request + $client = $this->client; + $endpoint = $this->helper->endpoint($this->getConfigKey()); + + $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getFileWithCorrectMimeType()); + $response = $client->getResponse(); + + $this->assertTrue($response->isSuccessful()); + $this->assertEquals($response->headers->get('Content-Type'), 'application/json'); + $this->assertCount(1, $this->getUploadedFiles()); + + foreach ($this->getUploadedFiles() as $file) { + $this->assertTrue($file->isFile()); + $this->assertTrue($file->isReadable()); + $this->assertEquals(128, $file->getSize()); + } + } + + public function testAgainstIncorrectMimeType() + { + $this->markTestSkipped('Mock mime type getter.'); + + // assemble a request + $client = $this->client; + $endpoint = $this->helper->endpoint($this->getConfigKey()); + + $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getFileWithIncorrectMimeType()); + $response = $client->getResponse(); + + //$this->assertTrue($response->isNotSuccessful()); + $this->assertEquals($response->headers->get('Content-Type'), 'application/json'); + $this->assertCount(0, $this->getUploadedFiles()); + } + protected function getConfigKey() { return 'blueimp_validation'; @@ -19,42 +123,42 @@ class BlueimpValidationTest extends AbstractValidationTest protected function getOversizedFile() { - return array(new UploadedFile( + return array('files' => array(new UploadedFile( $this->createTempFile(512), 'cat.ok', 'text/plain', 512 - )); + ))); } protected function getFileWithCorrectExtension() { - return array(new UploadedFile( + return array('files' => array(new UploadedFile( $this->createTempFile(128), 'cat.ok', 'text/plain', 128 - )); + ))); } protected function getFileWithIncorrectExtension() { - return array(new UploadedFile( + return array('files' => array(new UploadedFile( $this->createTempFile(128), 'cat.fail', 'text/plain', 128 - )); + ))); } protected function getFileWithCorrectMimeType() { - return array(new UploadedFile( + return array('files' => array(new UploadedFile( $this->createTempFile(128), 'cat.ok', 'image/jpg', 128 - )); + ))); } protected function getFileWithIncorrectMimeType()
0