From 5324b5a3a4a8fac9a3ab59979b77822cd4318a78 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Tue, 10 Dec 2013 20:17:48 +0100 Subject: [PATCH 01/54] Started to integrate propel [WIP] --- Adapter/AdapterInterface.php | 22 ++- Adapter/ODM/MongoDB/MongoDBAdapter.php | 24 ++-- Adapter/ORM/DoctrineORMAdapter.php | 24 ++-- Adapter/Propel/PropelAdapter.php | 38 ++++++ .../CompilerPass/RegisterPropelModelsPass.php | 32 +++++ DependencyInjection/Configuration.php | 14 +- DependencyInjection/VichUploaderExtension.php | 51 +++---- EventListener/DoctrineUploaderListener.php | 119 ++++++++++++++++ EventListener/PropelUploaderListener.php | 87 ++++++++++++ EventListener/UploaderListener.php | 129 ------------------ Handler/UploadHandler.php | 55 ++++++++ Injector/FileInjector.php | 8 +- Mapping/MappingReader.php | 5 + Metadata/Driver/AbstractFileDriver.php | 69 ++++++++++ Metadata/Driver/Chain.php | 51 +++++++ Metadata/Driver/FileLocator.php | 27 +++- Metadata/Driver/Yaml.php | 26 ++-- Resources/config/listener.xml | 18 ++- Resources/config/mapping.xml | 2 +- Storage/AbstractStorage.php | 4 +- .../ODM/MongoDB/MongoDBAdapterTest.php | 6 +- Tests/Adapter/ORM/DoctrineORMAdapterTest.php | 4 +- Tests/EventListener/UploaderListenerTest.php | 16 +-- VichUploaderBundle.php | 12 ++ composer.json | 1 + 25 files changed, 621 insertions(+), 223 deletions(-) create mode 100644 Adapter/Propel/PropelAdapter.php create mode 100644 DependencyInjection/CompilerPass/RegisterPropelModelsPass.php create mode 100644 EventListener/DoctrineUploaderListener.php create mode 100644 EventListener/PropelUploaderListener.php delete mode 100644 EventListener/UploaderListener.php create mode 100644 Handler/UploadHandler.php create mode 100644 Metadata/Driver/AbstractFileDriver.php create mode 100644 Metadata/Driver/Chain.php diff --git a/Adapter/AdapterInterface.php b/Adapter/AdapterInterface.php index 3d5fcc18..b55d485d 100644 --- a/Adapter/AdapterInterface.php +++ b/Adapter/AdapterInterface.php @@ -2,8 +2,6 @@ namespace Vich\UploaderBundle\Adapter; -use Doctrine\Common\EventArgs; - /** * AdapterInterface. * @@ -12,26 +10,26 @@ interface AdapterInterface { /** - * Gets the mapped object from the event arguments. + * Gets the mapped object from an event. * - * @param EventArgs $e The event arguments. - * @return object The mapped object. + * @param object $event The event argument. + * @return object The mapped object. */ - public function getObjectFromArgs(EventArgs $e); + public function getObjectFromEvent($event); /** - * Recomputes the change set for the object. + * Recomputes the change set for the given object. * - * @param EventArgs $e The event arguments. + * @param object $event The event arguments. */ - public function recomputeChangeSet(EventArgs $e); + public function recomputeChangeSet($event); /** - * Gets the reflection class for the object taking + * Gets the reflection class for the object, taking * proxies into account. * - * @param object $obj The object. + * @param object $object The object. * @return \ReflectionClass The reflection class. */ - public function getReflectionClass($obj); + public function getReflectionClass($object); } diff --git a/Adapter/ODM/MongoDB/MongoDBAdapter.php b/Adapter/ODM/MongoDB/MongoDBAdapter.php index 96a95f84..6a5c21bd 100644 --- a/Adapter/ODM/MongoDB/MongoDBAdapter.php +++ b/Adapter/ODM/MongoDB/MongoDBAdapter.php @@ -3,7 +3,6 @@ namespace Vich\UploaderBundle\Adapter\ODM\MongoDB; use Vich\UploaderBundle\Adapter\AdapterInterface; -use Doctrine\Common\EventArgs; use Doctrine\ODM\MongoDB\Proxy\Proxy; /** @@ -16,31 +15,34 @@ class MongoDBAdapter implements AdapterInterface /** * {@inheritDoc} */ - public function getObjectFromArgs(EventArgs $e) + public function getObjectFromEvent($event) { - return $e->getDocument(); + /* @var $event \Doctrine\Common\EventArgs */ + + return $event->getDocument(); } /** * {@inheritDoc} */ - public function recomputeChangeSet(EventArgs $e) + public function recomputeChangeSet($event) { - $obj = $this->getObjectFromArgs($e); + /* @var $event \Doctrine\Common\EventArgs */ + $object = $this->getObjectFromEvent($event); - $dm = $e->getDocumentManager(); + $dm = $event->getDocumentManager(); $uow = $dm->getUnitOfWork(); - $metadata = $dm->getClassMetadata(get_class($obj)); - $uow->recomputeSingleDocumentChangeSet($metadata, $obj); + $metadata = $dm->getClassMetadata(get_class($object)); + $uow->recomputeSingleDocumentChangeSet($metadata, $object); } /** * {@inheritDoc} */ - public function getReflectionClass($obj) + public function getReflectionClass($object) { - if ($obj instanceof Proxy) { - return new \ReflectionClass(get_parent_class($obj)); + if ($object instanceof Proxy) { + return new \ReflectionClass(get_parent_class($object)); } return new \ReflectionClass($obj); diff --git a/Adapter/ORM/DoctrineORMAdapter.php b/Adapter/ORM/DoctrineORMAdapter.php index 325c2a35..8ffbd1be 100644 --- a/Adapter/ORM/DoctrineORMAdapter.php +++ b/Adapter/ORM/DoctrineORMAdapter.php @@ -3,7 +3,6 @@ namespace Vich\UploaderBundle\Adapter\ORM; use Vich\UploaderBundle\Adapter\AdapterInterface; -use Doctrine\Common\EventArgs; use Doctrine\Common\Persistence\Proxy; /** @@ -16,31 +15,34 @@ class DoctrineORMAdapter implements AdapterInterface /** * {@inheritDoc} */ - public function getObjectFromArgs(EventArgs $e) + public function getObjectFromEvent($event) { - return $e->getEntity(); + /* @var $event \Doctrine\Common\EventArgs */ + + return $event->getEntity(); } /** * {@inheritDoc} */ - public function recomputeChangeSet(EventArgs $e) + public function recomputeChangeSet($event) { - $obj = $this->getObjectFromArgs($e); + /* @var $event \Doctrine\Common\EventArgs */ + $object = $this->getObjectFromEvent($event); - $em = $e->getEntityManager(); + $em = $event->getEntityManager(); $uow = $em->getUnitOfWork(); - $metadata = $em->getClassMetadata(get_class($obj)); - $uow->recomputeSingleEntityChangeSet($metadata, $obj); + $metadata = $em->getClassMetadata(get_class($object)); + $uow->recomputeSingleEntityChangeSet($metadata, $object); } /** * {@inheritDoc} */ - public function getReflectionClass($obj) + public function getReflectionClass($object) { - if ($obj instanceof Proxy) { - return new \ReflectionClass(get_parent_class($obj)); + if ($object instanceof Proxy) { + return new \ReflectionClass(get_parent_class($object)); } return new \ReflectionClass($obj); diff --git a/Adapter/Propel/PropelAdapter.php b/Adapter/Propel/PropelAdapter.php new file mode 100644 index 00000000..ec505b43 --- /dev/null +++ b/Adapter/Propel/PropelAdapter.php @@ -0,0 +1,38 @@ + + */ +class PropelAdapter implements AdapterInterface +{ + /** + * {@inheritDoc} + */ + public function getObjectFromEvent($event) + { + /* @var $event \Symfony\Component\EventDispatcher\GenericEvent */ + + return $event->getSubject(); + } + + /** + * {@inheritDoc} + */ + public function recomputeChangeSet($event) + { + } + + /** + * {@inheritDoc} + */ + public function getReflectionClass($object) + { + return new \ReflectionClass($object); + } +} diff --git a/DependencyInjection/CompilerPass/RegisterPropelModelsPass.php b/DependencyInjection/CompilerPass/RegisterPropelModelsPass.php new file mode 100644 index 00000000..3fb0bce8 --- /dev/null +++ b/DependencyInjection/CompilerPass/RegisterPropelModelsPass.php @@ -0,0 +1,32 @@ + + */ +class RegisterPropelModelsPass implements CompilerPassInterface +{ + /** + * {@inheritdoc} + */ + public function process(ContainerBuilder $container) + { + if ($container->getParameter('vich_uploader.driver') !== 'propel') { + return; + } + + $propelListener = $container->getDefinition('vich_uploader.listener.uploader.propel'); + $mapping = $container->get('vich_uploader.mapping_reader'); + foreach ($mapping->getUploadableClasses() as $class) { + $propelListener->addTag('propel.event_subscriber', array( + 'class' => $class + )); + } + } +} diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index aa02d757..a158761c 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -22,9 +22,21 @@ public function getConfigTreeBuilder() $tb = new TreeBuilder(); $root = $tb->root('vich_uploader'); + $supportedDbDrivers = array('orm', 'odm', 'propel'); + $root ->children() - ->scalarNode('db_driver')->isRequired()->end() + ->scalarNode('db_driver') + ->isRequired() + ->beforeNormalization() + ->ifString() + ->then(function ($v) { return strtolower($v); }) + ->end() + ->validate() + ->ifNotInArray($supportedDbDrivers) + ->thenInvalid('The db driver %s is not supported. Please choose one of ' . implode(', ', $supportedDbDrivers)) + ->end() + ->end() ->scalarNode('storage')->defaultValue('vich_uploader.storage.file_system')->end() ->scalarNode('twig')->defaultTrue()->end() ->scalarNode('gaufrette')->defaultFalse()->end() diff --git a/DependencyInjection/VichUploaderExtension.php b/DependencyInjection/VichUploaderExtension.php index b6f6512d..7ddd2848 100644 --- a/DependencyInjection/VichUploaderExtension.php +++ b/DependencyInjection/VichUploaderExtension.php @@ -3,6 +3,7 @@ namespace Vich\UploaderBundle\DependencyInjection; use Symfony\Component\HttpKernel\DependencyInjection\Extension; +use Symfony\Component\DependencyInjection\Alias; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader\XmlFileLoader; use Symfony\Component\Config\FileLocator; @@ -20,16 +21,17 @@ class VichUploaderExtension extends Extension * @var array $tagMap */ protected $tagMap = array( - 'orm' => 'doctrine.event_subscriber', - 'mongodb' => 'doctrine_mongodb.odm.event_subscriber' + 'orm' => 'doctrine.event_subscriber', + 'mongodb' => 'doctrine_mongodb.odm.event_subscriber', ); /** * @var array $adapterMap */ protected $adapterMap = array( - 'orm' => 'Vich\UploaderBundle\Adapter\ORM\DoctrineORMAdapter', - 'mongodb' => 'Vich\UploaderBundle\Adapter\ODM\MongoDB\MongoDBAdapter' + 'orm' => 'Vich\UploaderBundle\Adapter\ORM\DoctrineORMAdapter', + 'mongodb' => 'Vich\UploaderBundle\Adapter\ODM\MongoDB\MongoDBAdapter', + 'propel' => 'Vich\UploaderBundle\Adapter\Propel\PropelAdapter' ); /** @@ -47,17 +49,28 @@ public function load(array $configs, ContainerBuilder $container) } $configuration = new Configuration(); - $config = $this->processConfiguration($configuration, $configs); - $driver = strtolower($config['db_driver']); - if (!in_array($driver, array_keys($this->tagMap))) { - throw new \InvalidArgumentException(sprintf( - 'Invalid "db_driver" configuration option specified: "%s"', - $driver - )); + $this->loadServicesFiles($container, $config); + $this->registerMetadataDirectories($container, $config); + $this->registerCacheStrategy($container, $config); + + // define a few parameters + $container->setParameter('vich_uploader.driver', $config['db_driver']); + $container->setParameter('vich_uploader.mappings', $config['mappings']); + $container->setParameter('vich_uploader.storage_service', $config['storage']); + $container->setParameter('vich_uploader.adapter.class', $this->adapterMap[$config['db_driver']]); + + // choose the right listener + if ($config['db_driver'] !== 'propel') { + $container->getDefinition('vich_uploader.listener.uploader.'.$config['db_driver'])->addTag($this->tagMap[$config['db_driver']]); } + $container->setAlias('vich_uploader.listener.uploader', 'vich_uploader.listener.uploader.'.$config['db_driver']); + } + + protected function loadServicesFiles(ContainerBuilder $container, array $config) + { $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $toLoad = array( @@ -75,16 +88,6 @@ public function load(array $configs, ContainerBuilder $container) if ($config['twig']) { $loader->load('twig.xml'); } - - $mappings = isset($config['mappings']) ? $config['mappings'] : array(); - $container->setParameter('vich_uploader.mappings', $mappings); - - $container->setParameter('vich_uploader.storage_service', $config['storage']); - $container->setParameter('vich_uploader.adapter.class', $this->adapterMap[$driver]); - $container->getDefinition('vich_uploader.listener.uploader')->addTag($this->tagMap[$driver]); - - $this->registerMetadataDirectories($container, $config); - $this->registerCacheStrategy($container, $config); } protected function registerMetadataDirectories(ContainerBuilder $container, array $config) @@ -140,10 +143,8 @@ protected function registerCacheStrategy(ContainerBuilder $container, array $con ; $dir = $container->getParameterBag()->resolveValue($config['metadata']['file_cache']['dir']); - if (!file_exists($dir)) { - if (!$rs = @mkdir($dir, 0777, true)) { - throw new \RuntimeException(sprintf('Could not create cache directory "%s".', $dir)); - } + if (!file_exists($dir) && !@mkdir($dir, 0777, true)) { + throw new \RuntimeException(sprintf('Could not create cache directory "%s".', $dir)); } } else { $container->setAlias('vich_uploader.metadata.cache', new Alias($config['metadata']['cache'], false)); diff --git a/EventListener/DoctrineUploaderListener.php b/EventListener/DoctrineUploaderListener.php new file mode 100644 index 00000000..41292a91 --- /dev/null +++ b/EventListener/DoctrineUploaderListener.php @@ -0,0 +1,119 @@ + + */ +class DoctrineUploaderListener implements EventSubscriber +{ + /** + * @var AdapterInterface $adapter + */ + protected $adapter; + + /** + * @var MappingReader $mapping + */ + protected $mapping; + + /** + * @var UploaderHandler $handler + */ + protected $handler; + + /** + * Constructs a new instance of UploaderListener. + * + * @param AdapterInterface $adapter The adapter. + * @param MappingReader $mapping The mapping reader. + * @param UploaderHandler $handler The upload handler. + */ + public function __construct(AdapterInterface $adapter, MappingReader $mapping, UploadHandler $handler) + { + $this->adapter = $adapter; + $this->mapping = $mapping; + $this->handler = $handler; + } + + /** + * The events the listener is subscribed to. + * + * @return array The array of events. + */ + public function getSubscribedEvents() + { + return array( + 'prePersist', + 'preUpdate', + 'postLoad', + 'postRemove', + ); + } + + /** + * Checks for file to upload. + * + * @param EventArgs $event The event. + */ + public function prePersist(EventArgs $event) + { + $obj = $this->adapter->getObjectFromEvent($event); + + if ($this->mapping->isUploadable($this->adapter->getReflectionClass($obj))) { + $this->handler->handleUpload($obj); + } + } + + /** + * Update the file and file name if necessary. + * + * @param EventArgs $event The event. + */ + public function preUpdate(EventArgs $event) + { + $obj = $this->adapter->getObjectFromEvent($event); + + if ($this->mapping->isUploadable($this->adapter->getReflectionClass($obj))) { + $this->handler->handleUpload($obj); + $this->adapter->recomputeChangeSet($event); + } + } + + /** + * Populates uploadable fields from filename properties. + * + * @param EventArgs $event The event. + */ + public function postLoad(EventArgs $event) + { + $obj = $this->adapter->getObjectFromEvent($event); + + if ($this->mapping->isUploadable($this->adapter->getReflectionClass($obj))) { + $this->handler->handleHydration($obj); + } + } + + /** + * Removes the file if necessary. + * + * @param EventArgs $event The event. + */ + public function postRemove(EventArgs $event) + { + $obj = $this->adapter->getObjectFromEvent($event); + + if ($this->mapping->isUploadable($this->adapter->getReflectionClass($obj))) { + $this->handler->handleDeletion($obj); + } + } +} diff --git a/EventListener/PropelUploaderListener.php b/EventListener/PropelUploaderListener.php new file mode 100644 index 00000000..f00cb817 --- /dev/null +++ b/EventListener/PropelUploaderListener.php @@ -0,0 +1,87 @@ + + */ +class PropelUploaderListener implements EventSubscriberInterface +{ + /** + * @var AdapterInterface $adapter + */ + protected $adapter; + + /** + * @var UploaderHandler $handler + */ + protected $handler; + + /** + * Constructs a new instance of UploaderListener. + * + * @param AdapterInterface $adapter The adapter. + * @param UploaderHandler $handler The upload handler. + */ + public function __construct(AdapterInterface $adapter, UploadHandler $handler) + { + $this->adapter = $adapter; + $this->handler = $handler; + } + + /** + * The events the listener is subscribed to. + * + * @return array The array of events. + */ + public static function getSubscribedEvents() + { + return array( + 'propel.pre_insert' => 'onUpload', + 'propel.pre_update' => 'onUpload', + 'propel.post_delete' => 'onDelete', + 'propel.construct' => 'onConstruct', + ); + } + + /** + * Update the file and file name if necessary. + * + * @param GenericEvent $event The event. + */ + public function onUpload(GenericEvent $event) + { + $obj = $this->adapter->getObjectFromEvent($event); + $this->handler->handleUpload($obj); + } + + /** + * Populates uploadable fields from filename properties. + * + * @param GenericEvent $event The event. + */ + public function onConstruct(GenericEvent $event) + { + $obj = $this->adapter->getObjectFromEvent($event); + $this->handler->handleHydration($obj); + } + + /** + * Removes the file when the object is deleted. + * + * @param GenericEvent $event The event. + */ + public function onDelete(GenericEvent $event) + { + $obj = $this->adapter->getObjectFromEvent($event); + $this->handler->handleDeletion($obj); + } +} diff --git a/EventListener/UploaderListener.php b/EventListener/UploaderListener.php deleted file mode 100644 index 12e06bbf..00000000 --- a/EventListener/UploaderListener.php +++ /dev/null @@ -1,129 +0,0 @@ - - */ -class UploaderListener implements EventSubscriber -{ - /** - * @var \Vich\UploaderBundle\Adapter\AdapterInterface $adapter - */ - protected $adapter; - - /** - * @var \Vich\UploaderBundle\Mapping\MappingReader $mapping - */ - protected $mapping; - - /** - * @var \Vich\UploaderBundle\Storage\StorageInterface $storage - */ - protected $storage; - - /** - * @var \Vich\UploaderBundle\Injector\FileInjectorInterface $injector - */ - protected $injector; - - /** - * Constructs a new instance of UploaderListener. - * - * @param \Vich\UploaderBundle\Adapter\AdapterInterface $adapter The adapter. - * @param \Vich\UploaderBundle\Mapping\MappingReader $mapping The mapping reader. - * @param \Vich\UploaderBundle\Storage\StorageInterface $storage The storage. - * @param \Vich\UploaderBundle\Injector\FileInjectorInterface $injector The injector. - */ - public function __construct(AdapterInterface $adapter, MappingReader $mapping, StorageInterface $storage, FileInjectorInterface $injector) - { - $this->adapter = $adapter; - $this->mapping = $mapping; - $this->storage = $storage; - $this->injector = $injector; - } - - /** - * The events the listener is subscribed to. - * - * @return array The array of events. - */ - public function getSubscribedEvents() - { - return array( - 'prePersist', - 'preUpdate', - 'postLoad', - 'postRemove', - ); - } - - /** - * Checks for file to upload. - * - * @param \Doctrine\Common\EventArgs $args The event arguments. - */ - public function prePersist(EventArgs $args) - { - $obj = $this->adapter->getObjectFromArgs($args); - - if ($this->mapping->isUploadable($this->adapter->getReflectionClass($obj))) { - $this->storage->upload($obj); - $this->injector->injectFiles($obj); - } - } - - /** - * Update the file and file name if necessary. - * - * @param EventArgs $args The event arguments. - */ - public function preUpdate(EventArgs $args) - { - $obj = $this->adapter->getObjectFromArgs($args); - - if ($this->mapping->isUploadable($this->adapter->getReflectionClass($obj))) { - $this->storage->upload($obj); - $this->injector->injectFiles($obj); - $this->adapter->recomputeChangeSet($args); - } - } - - /** - * Populates uploadable fields from filename properties - * if necessary. - * - * @param \Doctrine\Common\EventArgs $args - */ - public function postLoad(EventArgs $args) - { - $obj = $this->adapter->getObjectFromArgs($args); - - if ($this->mapping->isUploadable($this->adapter->getReflectionClass($obj))) { - $this->injector->injectFiles($obj); - } - } - - /** - * Removes the file if necessary. - * - * @param EventArgs $args The event arguments. - */ - public function postRemove(EventArgs $args) - { - $obj = $this->adapter->getObjectFromArgs($args); - - if ($this->mapping->isUploadable($this->adapter->getReflectionClass($obj))) { - $this->storage->remove($obj); - } - } -} diff --git a/Handler/UploadHandler.php b/Handler/UploadHandler.php new file mode 100644 index 00000000..dcf9e82a --- /dev/null +++ b/Handler/UploadHandler.php @@ -0,0 +1,55 @@ + + */ +class UploadHandler +{ + /** + * @var \Vich\UploaderBundle\Storage\StorageInterface $storage + */ + protected $storage; + + /** + * @var \Vich\UploaderBundle\Injector\FileInjectorInterface $injector + */ + protected $injector; + + /** + * Constructs a new instance of UploaderListener. + * + * @param \Vich\UploaderBundle\Storage\StorageInterface $storage The storage. + * @param \Vich\UploaderBundle\Injector\FileInjectorInterface $injector The injector. + */ + public function __construct(StorageInterface $storage, FileInjectorInterface $injector) + { + $this->storage = $storage; + $this->injector = $injector; + } + + /** + * Checks for file to upload. + */ + public function handleUpload($obj) + { + $this->storage->upload($obj); + $this->injector->injectFiles($obj); + } + + public function handleHydration($obj) + { + $this->injector->injectFiles($obj); + } + + public function handleDeletion($obj) + { + $this->storage->remove($obj); + } +} diff --git a/Injector/FileInjector.php b/Injector/FileInjector.php index 1f5f8beb..325443ee 100644 --- a/Injector/FileInjector.php +++ b/Injector/FileInjector.php @@ -6,6 +6,8 @@ use Vich\UploaderBundle\Mapping\PropertyMappingFactory; use Vich\UploaderBundle\Storage\StorageInterface; use Symfony\Component\HttpFoundation\File\File; +use Symfony\Component\PropertyAccess\PropertyAccess; + /** * FileInjector. * @@ -53,10 +55,8 @@ public function injectFiles($obj) continue; } - $mapping->getProperty()->setValue( - $obj, - new File($path, false) - ); + $prop = PropertyAccess::getPropertyAccessor(); + $prop->setValue($obj, $field, new File($path, false)); } } } diff --git a/Mapping/MappingReader.php b/Mapping/MappingReader.php index 89752f70..9b1240f0 100644 --- a/Mapping/MappingReader.php +++ b/Mapping/MappingReader.php @@ -40,6 +40,11 @@ public function isUploadable(\ReflectionClass $class) return $metadata !== null; } + public function getUploadableClasses() + { + return $this->reader->getAllClassNames(); + } + /** * Attempts to read the uploadable fields. * diff --git a/Metadata/Driver/AbstractFileDriver.php b/Metadata/Driver/AbstractFileDriver.php new file mode 100644 index 00000000..4c02c2ba --- /dev/null +++ b/Metadata/Driver/AbstractFileDriver.php @@ -0,0 +1,69 @@ + + */ +abstract class AbstractFileDriver implements AdvancedDriverInterface +{ + /** + * @var FileLocatorInterface|FileLocator + */ + private $locator; + + public function __construct(FileLocatorInterface $locator) + { + $this->locator = $locator; + } + + public function loadMetadataForClass(\ReflectionClass $class) + { + if (null === $path = $this->locator->findFileForClass($class, $this->getExtension())) { + return null; + } + + return $this->loadMetadataFromFile($path, $class); + } + + /** + * {@inheritDoc} + */ + public function getAllClassNames() + { + if (!$this->locator instanceof AdvancedFileLocatorInterface) { + throw new \RuntimeException('Locator "%s" must be an instance of "AdvancedFileLocatorInterface".'); + } + + $classNames = array(); + foreach ($this->locator->findAllClasses($this->getExtension()) as $file) { + $metadata = $this->loadMetadataFromFile($file->getRealpath()); + $classNames[] = $metadata->name; + } + + return $classNames; + } + + /** + * Parses the content of the file, and converts it to the desired metadata. + * + * @param string $file + * @param \ReflectionClass $class + * + * @return \MetaData\ClassMetadata|null + */ + abstract protected function loadMetadataFromFile($file, \ReflectionClass $class = null); + + /** + * Returns the extension of the file. + * + * @return string + */ + abstract protected function getExtension(); +} diff --git a/Metadata/Driver/Chain.php b/Metadata/Driver/Chain.php new file mode 100644 index 00000000..d347fcd3 --- /dev/null +++ b/Metadata/Driver/Chain.php @@ -0,0 +1,51 @@ +drivers = $drivers; + } + + public function addDriver(DriverInterface $driver) + { + $this->drivers[] = $driver; + } + + public function loadMetadataForClass(\ReflectionClass $class) + { + foreach ($this->drivers as $driver) { + if (null !== ($metadata = $driver->loadMetadataForClass($class))) { + return $metadata; + } + } + + return null; + } + + /** + * {@inheritDoc} + */ + public function getAllClassNames() + { + $classes = array(); + foreach ($this->drivers as $driver) { + if (!$driver instanceof AdvancedDriverInterface) { + continue; + } + + $driverClasses = $driver->getAllClassNames(); + if (!empty($driverClasses)) { + $classes = array_merge($classes, $driverClasses); + } + } + + return $classes; + } +} diff --git a/Metadata/Driver/FileLocator.php b/Metadata/Driver/FileLocator.php index c0f0e370..28d19acf 100644 --- a/Metadata/Driver/FileLocator.php +++ b/Metadata/Driver/FileLocator.php @@ -2,10 +2,10 @@ namespace Vich\UploaderBundle\Metadata\Driver; -use Metadata\Driver\FileLocatorInterface; +use Metadata\Driver\AdvancedFileLocatorInterface; use Symfony\Component\Finder\Finder; -class FileLocator implements FileLocatorInterface +class FileLocator implements AdvancedFileLocatorInterface { private $dirs; @@ -27,12 +27,13 @@ public function getDirs() */ public function findFileForClass(\ReflectionClass $class, $extension) { + $finder = new Finder(); + foreach ($this->dirs as $prefix => $dir) { if ('' !== $prefix && 0 !== strpos($class->getNamespaceName(), $prefix)) { continue; } - $finder = new Finder(); $files = $finder->files()->in($dir)->name(sprintf('*%s*.%s', $class->getShortName(), $extension)); if (count($files) !== 1) { @@ -46,4 +47,24 @@ public function findFileForClass(\ReflectionClass $class, $extension) return null; } + + /** + * Finds all possible metadata files. + * + * @param string $extension + * + * @return array + */ + public function findAllClasses($extension) + { + $files = array(); + $finder = new Finder(); + + foreach ($this->dirs as $dir) { + $results = $finder->files()->in($dir)->name('*.' . $extension); + $files = array_merge(iterator_to_array($results), $files); + } + + return array_unique($files); + } } diff --git a/Metadata/Driver/Yaml.php b/Metadata/Driver/Yaml.php index 188ac847..380ae314 100644 --- a/Metadata/Driver/Yaml.php +++ b/Metadata/Driver/Yaml.php @@ -2,7 +2,6 @@ namespace Vich\UploaderBundle\Metadata\Driver; -use Metadata\Driver\AbstractFileDriver; use Symfony\Component\Yaml\Yaml as YmlParser; use Vich\UploaderBundle\Metadata\ClassMetadata; @@ -17,17 +16,13 @@ class Yaml extends AbstractFileDriver /** * {@inheritDoc} */ - protected function loadMetadataFromFile(\ReflectionClass $class, $file) + protected function loadMetadataFromFile($file, \ReflectionClass $class = null) { $config = $this->loadMappingFile($file); + $className = $this->guessClassName($config, $class); + $metadata = new ClassMetadata($className); - if (!isset($config[$class->name])) { - throw new \RuntimeException(sprintf('Expected metadata for class %s to be defined in %s.', $class->name, $file)); - } - - $metadata = new ClassMetadata($class->name); - - foreach ($config[$class->name] as $field => $mappingData) { + foreach ($config[$className] as $field => $mappingData) { $fieldMetadata = array( 'mapping' => $mappingData['mapping'], 'propertyName' => $field, @@ -52,4 +47,17 @@ protected function getExtension() { return 'yml'; } + + protected function guessClassName(array $config, \ReflectionClass $class = null) + { + if ($class !== null) { + if (!isset($config[$class->name])) { + throw new \RuntimeException(sprintf('Expected metadata for class %s to be defined in %s.', $class->name, $file)); + } + + return $class->name; + } + + return current(array_keys($config)); + } } diff --git a/Resources/config/listener.xml b/Resources/config/listener.xml index 785a7d70..21ed46d8 100644 --- a/Resources/config/listener.xml +++ b/Resources/config/listener.xml @@ -6,13 +6,25 @@ - - - + + + + + + + + + + + + + + + diff --git a/Resources/config/mapping.xml b/Resources/config/mapping.xml index 26141131..cfd49a14 100644 --- a/Resources/config/mapping.xml +++ b/Resources/config/mapping.xml @@ -20,7 +20,7 @@ - + diff --git a/Storage/AbstractStorage.php b/Storage/AbstractStorage.php index 62e4a936..584293a2 100644 --- a/Storage/AbstractStorage.php +++ b/Storage/AbstractStorage.php @@ -5,6 +5,7 @@ use Vich\UploaderBundle\Mapping\PropertyMappingFactory; use Vich\UploaderBundle\Mapping\PropertyMapping; use Symfony\Component\HttpFoundation\File\UploadedFile; +use Symfony\Component\PropertyAccess\PropertyAccess; /** * FileSystemStorage. @@ -69,7 +70,8 @@ public function upload($obj) $this->doUpload($file, $dir, $name); - $mapping->getFileNameProperty()->setValue($obj, $name); + $prop = PropertyAccess::getPropertyAccessor(); + $prop->setValue($obj, $mapping->getFileNamePropertyName(), $name); } } diff --git a/Tests/Adapter/ODM/MongoDB/MongoDBAdapterTest.php b/Tests/Adapter/ODM/MongoDB/MongoDBAdapterTest.php index bf260d7b..f5f774e8 100644 --- a/Tests/Adapter/ODM/MongoDB/MongoDBAdapterTest.php +++ b/Tests/Adapter/ODM/MongoDB/MongoDBAdapterTest.php @@ -14,9 +14,9 @@ class MongoDBAdapterTest extends \PHPUnit_Framework_TestCase { /** - * Test the getObjectFromArgs method. + * Test the getObjectFromEvent method. */ - public function testGetObjectFromArgs() + public function testGetObjectFromEvent() { if (!class_exists('Doctrine\ODM\MongoDB\Event\LifecycleEventArgs')) { $this->markTestSkipped('Doctrine\ODM\MongoDB\Event\LifecycleEventArgs does not exist.'); @@ -33,7 +33,7 @@ public function testGetObjectFromArgs() $adapter = new MongoDBAdapter(); - $this->assertEquals($entity, $adapter->getObjectFromArgs($args)); + $this->assertEquals($entity, $adapter->getObjectFromEvent($args)); } } diff --git a/Tests/Adapter/ORM/DoctrineORMAdapterTest.php b/Tests/Adapter/ORM/DoctrineORMAdapterTest.php index 2741deac..3dc9768c 100644 --- a/Tests/Adapter/ORM/DoctrineORMAdapterTest.php +++ b/Tests/Adapter/ORM/DoctrineORMAdapterTest.php @@ -14,7 +14,7 @@ class DoctrineORMAdapterTest extends \PHPUnit_Framework_TestCase { /** - * Test the getObjectFromArgs method. + * Test the getObjectFromEvent method. */ public function testGetObjectFromArgs() { @@ -33,7 +33,7 @@ public function testGetObjectFromArgs() $adapter = new DoctrineORMAdapter(); - $this->assertEquals($entity, $adapter->getObjectFromArgs($args)); + $this->assertEquals($entity, $adapter->getObjectFromEvent($args)); } } diff --git a/Tests/EventListener/UploaderListenerTest.php b/Tests/EventListener/UploaderListenerTest.php index 885d1bb6..3493d639 100644 --- a/Tests/EventListener/UploaderListenerTest.php +++ b/Tests/EventListener/UploaderListenerTest.php @@ -71,7 +71,7 @@ public function testPrePersist() $this->adapter ->expects($this->once()) - ->method('getObjectFromArgs') + ->method('getObjectFromEvent') ->will($this->returnValue($obj)); $this->adapter @@ -113,7 +113,7 @@ public function testPrePersistSkipsNonUploadable() $this->adapter ->expects($this->once()) - ->method('getObjectFromArgs') + ->method('getObjectFromEvent') ->will($this->returnValue($obj)); $this->adapter @@ -153,7 +153,7 @@ public function testPreUpdate() $this->adapter ->expects($this->once()) - ->method('getObjectFromArgs') + ->method('getObjectFromEvent') ->will($this->returnValue($obj)); $this->adapter @@ -200,7 +200,7 @@ public function testPreUpdateSkipsNonUploadable() $this->adapter ->expects($this->once()) - ->method('getObjectFromArgs') + ->method('getObjectFromEvent') ->will($this->returnValue($obj)); $this->adapter @@ -244,7 +244,7 @@ public function testPostLoad() $this->adapter ->expects($this->once()) - ->method('getObjectFromArgs') + ->method('getObjectFromEvent') ->will($this->returnValue($obj)); $this->adapter @@ -281,7 +281,7 @@ public function testPostLoadSkipsNonUploadable() $this->adapter ->expects($this->once()) - ->method('getObjectFromArgs') + ->method('getObjectFromEvent') ->will($this->returnValue($obj)); $this->adapter @@ -317,7 +317,7 @@ public function testPostRemove() $this->adapter ->expects($this->once()) - ->method('getObjectFromArgs') + ->method('getObjectFromEvent') ->will($this->returnValue($obj)); $this->adapter @@ -354,7 +354,7 @@ public function testPostRemoveSkipsNonUploadable() $this->adapter ->expects($this->once()) - ->method('getObjectFromArgs') + ->method('getObjectFromEvent') ->will($this->returnValue($obj)); $this->adapter diff --git a/VichUploaderBundle.php b/VichUploaderBundle.php index 66dfd036..76642085 100644 --- a/VichUploaderBundle.php +++ b/VichUploaderBundle.php @@ -2,8 +2,11 @@ namespace Vich\UploaderBundle; +use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\HttpKernel\Bundle\Bundle; +use Vich\UploaderBundle\DependencyInjection\CompilerPass\RegisterPropelModelsPass; + /** * VichUploaderBundle. * @@ -11,4 +14,13 @@ */ class VichUploaderBundle extends Bundle { + /** + * {@inheritdoc} + */ + public function build(ContainerBuilder $container) + { + parent::build($container); + + $container->addCompilerPass(new RegisterPropelModelsPass()); + } } diff --git a/composer.json b/composer.json index 68a6925e..f8e837f5 100644 --- a/composer.json +++ b/composer.json @@ -29,6 +29,7 @@ "doctrine/doctrine-bundle": "*", "doctrine/mongodb-odm-bundle": "*", "knplabs/knp-gaufrette-bundle": "*", + "willdurand/propel-eventdispatcher-bundle": "~1.0", "symfony/yaml": "@stable" }, "autoload": { From db36ffc7954783422830158f44afcda480017522 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Tue, 10 Dec 2013 20:50:58 +0100 Subject: [PATCH 02/54] Use the PropertyAccess component to manipulate objects --- Injector/FileInjector.php | 17 +++-- Mapping/MappingReader.php | 2 + Mapping/PropertyMapping.php | 106 ++++++++++++++--------------- Mapping/PropertyMappingFactory.php | 37 +++++----- Storage/AbstractStorage.php | 33 ++++----- Storage/FileSystemStorage.php | 2 +- composer.json | 1 + 7 files changed, 98 insertions(+), 100 deletions(-) diff --git a/Injector/FileInjector.php b/Injector/FileInjector.php index 325443ee..17e3f823 100644 --- a/Injector/FileInjector.php +++ b/Injector/FileInjector.php @@ -2,11 +2,11 @@ namespace Vich\UploaderBundle\Injector; +use Symfony\Component\HttpFoundation\File\File; + use Vich\UploaderBundle\Injector\FileInjectorInterface; use Vich\UploaderBundle\Mapping\PropertyMappingFactory; use Vich\UploaderBundle\Storage\StorageInterface; -use Symfony\Component\HttpFoundation\File\File; -use Symfony\Component\PropertyAccess\PropertyAccess; /** * FileInjector. @@ -16,20 +16,20 @@ class FileInjector implements FileInjectorInterface { /** - * @var \Vich\UploaderBundle\Mapping\PropertyMappingFactory $factory + * @var PropertyMappingFactory $factory */ protected $factory; /** - * @var \Vich\UploaderBundle\Storage\StorageInterface + * @var StorageInterface */ protected $storage; /** * Constructs a new instance of FileInjector. * - * @param \Vich\UploaderBundle\Mapping\PropertyMappingFactory $factory The factory. - * @param \Vich\UploaderBundle\Storage\StorageInterface $storage Storage. + * @param PropertyMappingFactory $factory The factory. + * @param StorageInterface $storage Storage. */ public function __construct(PropertyMappingFactory $factory, StorageInterface $storage) { @@ -48,15 +48,14 @@ public function injectFiles($obj) continue; } - $field = $mapping->getProperty()->getName(); + $field = $mapping->getFilePropertyName(); try { $path = $this->storage->resolvePath($obj, $field); } catch (\InvalidArgumentException $e) { continue; } - $prop = PropertyAccess::getPropertyAccessor(); - $prop->setValue($obj, $field, new File($path, false)); + $mapping->setFile($obj, new File($path, false)); } } } diff --git a/Mapping/MappingReader.php b/Mapping/MappingReader.php index 9b1240f0..06561183 100644 --- a/Mapping/MappingReader.php +++ b/Mapping/MappingReader.php @@ -7,6 +7,8 @@ /** * MappingReader * + * @todo rename (MetadataReader?) + * * @author Kévin Gomez */ class MappingReader diff --git a/Mapping/PropertyMapping.php b/Mapping/PropertyMapping.php index d0a2dfb4..39b95e2d 100644 --- a/Mapping/PropertyMapping.php +++ b/Mapping/PropertyMapping.php @@ -2,6 +2,8 @@ namespace Vich\UploaderBundle\Mapping; +use Symfony\Component\PropertyAccess\PropertyAccess; + use Vich\UploaderBundle\Naming\NamerInterface; use Vich\UploaderBundle\Naming\DirectoryNamerInterface; @@ -12,16 +14,6 @@ */ class PropertyMapping { - /** - * @var \ReflectionProperty $property - */ - protected $property; - - /** - * @var \ReflectionProperty $fileNameProperty - */ - protected $fileNameProperty; - /** * @var NamerInterface $namer */ @@ -43,49 +35,33 @@ class PropertyMapping protected $mappingName; /** - * Gets the reflection property that represents the - * annotated property. - * - * @return \ReflectionProperty The property. + * @var string $filePropertyPath */ - public function getProperty() - { - return $this->property; - } + protected $filePropertyPath; /** - * Sets the reflection property that represents the annotated - * property. - * - * @param \ReflectionProperty $property The reflection property. + * @var string $fileNamePropertyPath */ - public function setProperty(\ReflectionProperty $property) - { - $this->property = $property; - $this->property->setAccessible(true); - } + protected $fileNamePropertyPath; /** - * Gets the reflection property that represents the property - * which holds the file name for the mapping. - * - * @return \ReflectionProperty The reflection property. + * @var PropertyAccess $accessor */ - public function getFileNameProperty() + protected $accessor; + + public function __construct($filePropertyPath, $fileNamePropertyPath) { - return $this->fileNameProperty; + $this->filePropertyPath = $filePropertyPath; + $this->fileNamePropertyPath = $fileNamePropertyPath; } - /** - * Sets the reflection property that represents the property - * which holds the file name for the mapping. - * - * @param \ReflectionProperty $fileNameProperty The reflection property. - */ - public function setFileNameProperty(\ReflectionProperty $fileNameProperty) + protected function getAccessor() { - $this->fileNameProperty = $fileNameProperty; - $this->fileNameProperty->setAccessible(true); + if ($this->accessor !== null) { + return $this->accessor; + } + + return $this->accessor = PropertyAccess::createPropertyAccessor(); } /** @@ -179,34 +155,56 @@ public function setMappingName($mappingName) } /** - * Gets the name of the annotated property. + * Gets the file property value for the given object. * - * @return string The name. + * @param object $obj The object. + * @return UploadedFile The file. */ - public function getPropertyName() + public function getFile($obj) { - return $this->property->getName(); + return $this->getAccessor()->getValue($obj, $this->filePropertyPath); } /** - * Gets the value of the annotated property. + * Modifies the file property value for the given object. * - * @param object $obj The object. - * @return UploadedFile The file. + * @param object $obj The object. + * @param UploadedFile $file The new file. + */ + public function setFile($obj, $file) + { + $this->getAccessor()->setValue($obj, $this->filePropertyPath, $file); + } + + /** + * Gets the fileName property of the given object. + * + * @param object $obj The object. + * @return string The filename. + */ + public function getFileName($obj) + { + return $this->getAccessor()->getValue($obj, $this->fileNamePropertyPath); + } + + /** + * Modifies the fileName property of the given object. + * + * @param object $obj The object. */ - public function getPropertyValue($obj) + public function setFileName($obj, $value) { - return $this->property->getValue($obj); + $this->getAccessor()->setValue($obj, $this->fileNamePropertyPath, $value); } /** - * Gets the configured file name property name. + * Gets the configured file property name. * * @return string The name. */ - public function getFileNamePropertyName() + public function getFilePropertyName() { - return $this->fileNameProperty->getName(); + return $this->filePropertyPath; } /** diff --git a/Mapping/PropertyMappingFactory.php b/Mapping/PropertyMappingFactory.php index ecb1da67..0f7584a8 100644 --- a/Mapping/PropertyMappingFactory.php +++ b/Mapping/PropertyMappingFactory.php @@ -2,12 +2,13 @@ namespace Vich\UploaderBundle\Mapping; -use Vich\UploaderBundle\Mapping\MappingReader; -use Vich\UploaderBundle\Mapping\PropertyMapping; -use Vich\UploaderBundle\Adapter\AdapterInterface; +use Doctrine\Common\Persistence\Proxy; use Symfony\Component\DependencyInjection\ContainerInterface; + +use Vich\UploaderBundle\Adapter\AdapterInterface; use Vich\UploaderBundle\Mapping\Annotation\UploadableField; -use Doctrine\Common\Persistence\Proxy; +use Vich\UploaderBundle\Mapping\MappingReader; +use Vich\UploaderBundle\Mapping\PropertyMapping; /** * PropertyMappingFactory. @@ -39,10 +40,10 @@ class PropertyMappingFactory /** * Constructs a new instance of PropertyMappingFactory. * - * @param \Symfony\Component\DependencyInjection\ContainerInterface $container The container. - * @param \Vich\UploaderBundle\Mapping\MappingReader $mapping The mapping mapping. - * @param \Vich\UploaderBundle\Adapter\AdapterInterface $adapter The adapter. - * @param array $mappings The configured mappings. + * @param ContainerInterface $container The container. + * @param MappingReader $mapping The mapping mapping. + * @param AdapterInterface $adapter The adapter. + * @param array $mappings The configured mappings. */ public function __construct(ContainerInterface $container, MappingReader $mapping, AdapterInterface $adapter, array $mappings) { @@ -62,6 +63,7 @@ public function __construct(ContainerInterface $container, MappingReader $mappin */ public function fromObject($obj) { + // @todo nothing to do here if ($obj instanceof Proxy) { $obj->__load(); } @@ -87,6 +89,7 @@ public function fromObject($obj) */ public function fromField($obj, $field) { + // @todo nothing to do here if ($obj instanceof Proxy) { $obj->__load(); } @@ -105,8 +108,8 @@ public function fromField($obj, $field) /** * Checks to see if the class is uploadable. * - * @param \ReflectionClass $class The class. - * @throws \InvalidArgumentException + * @param ReflectionClass $class The class. + * @throws InvalidArgumentException */ protected function checkUploadable(\ReflectionClass $class) { @@ -118,12 +121,12 @@ protected function checkUploadable(\ReflectionClass $class) /** * Creates the property mapping from the read annotation and configured mapping. * - * @param object $obj The object. - * @param string $fieldName The field name. - * @param \Vich\UploaderBundle\Annotation\UploadableField $mappingData The mapping data. + * @param object $obj The object. + * @param string $fieldName The field name. + * @param UploadableField $mappingData The mapping data. * - * @return PropertyMapping The property mapping. - * @throws \InvalidArgumentException + * @return PropertyMapping The property mapping. + * @throws InvalidArgumentException */ protected function createMapping($obj, $fieldName, array $mappingData) { @@ -137,9 +140,7 @@ protected function createMapping($obj, $fieldName, array $mappingData) $config = $this->mappings[$mappingData['mapping']]; - $mapping = new PropertyMapping(); - $mapping->setProperty($class->getProperty($mappingData['propertyName'] ?: $fieldName)); - $mapping->setFileNameProperty($class->getProperty($mappingData['fileNameProperty'])); + $mapping = new PropertyMapping($mappingData['propertyName'] ?: $fieldName, $mappingData['fileNameProperty']); $mapping->setMappingName($mappingData['mapping']); $mapping->setMapping($config); diff --git a/Storage/AbstractStorage.php b/Storage/AbstractStorage.php index 584293a2..9ac9c4e2 100644 --- a/Storage/AbstractStorage.php +++ b/Storage/AbstractStorage.php @@ -5,7 +5,6 @@ use Vich\UploaderBundle\Mapping\PropertyMappingFactory; use Vich\UploaderBundle\Mapping\PropertyMapping; use Symfony\Component\HttpFoundation\File\UploadedFile; -use Symfony\Component\PropertyAccess\PropertyAccess; /** * FileSystemStorage. @@ -47,31 +46,29 @@ public function upload($obj) { $mappings = $this->factory->fromObject($obj); foreach ($mappings as $mapping) { - $file = $mapping->getPropertyValue($obj); + $file = $mapping->getFile($obj); if ($file === null || !($file instanceof UploadedFile)) { continue; } - if ($mapping->getDeleteOnUpdate() && $mapping->getFileNameProperty()->getValue($obj)) { - $name = $mapping->getFileNameProperty()->getValue($obj); - $dir = $mapping->getUploadDir($obj, $mapping->getProperty()->getName()); + if ($mapping->getDeleteOnUpdate() && ($name = $mapping->getFileName($obj))) { + $dir = $mapping->getUploadDir($obj, $mapping->getFilePropertyName()); $this->doRemove($dir, $name); } if ($mapping->hasNamer()) { - $name = $mapping->getNamer()->name($obj, $mapping->getProperty()->getName()); + $name = $mapping->getNamer()->name($obj, $mapping->getFilePropertyName()); } else { $name = $file->getClientOriginalName(); } - $dir = $mapping->getUploadDir($obj, $mapping->getProperty()->getName()); + $dir = $mapping->getUploadDir($obj, $mapping->getFilePropertyName()); $this->doUpload($file, $dir, $name); - $prop = PropertyAccess::getPropertyAccessor(); - $prop->setValue($obj, $mapping->getFileNamePropertyName(), $name); + $mapping->setFileName($obj, $name); } } @@ -98,13 +95,13 @@ public function remove($obj) continue; } - $name = $mapping->getFileNameProperty()->getValue($obj); + $name = $mapping->getFileName($obj); if (null === $name) { continue; } - $dir = $mapping->getUploadDir($obj, $mapping->getProperty()->getName()); + $dir = $mapping->getUploadDir($obj, $mapping->getFilePropertyName()); $this->doRemove($dir, $name); } @@ -125,7 +122,7 @@ abstract protected function doResolvePath($dir, $name); */ public function resolvePath($obj, $field) { - list($mapping, $name) = $this->getFileNamePropertyValue($obj, $field); + list($mapping, $name) = $this->getFileName($obj, $field); $dir = $mapping->getUploadDir($obj, $field); return $this->doResolvePath($dir, $name); @@ -136,13 +133,13 @@ public function resolvePath($obj, $field) */ public function resolveUri($obj, $field) { - list($mapping, $name) = $this->getFileNamePropertyValue($obj, $field); + list($mapping, $filename) = $this->getFileName($obj, $field); $uriPrefix = $mapping->getUriPrefix(); - return $name ? ($uriPrefix . '/' . $name) : ''; + return $name ? ($uriPrefix . '/' . $filename) : ''; } - protected function getFileNamePropertyValue($obj, $field) + protected function getFileName($obj, $field) { $mapping = $this->factory->fromField($obj, $field); if (null === $mapping) { @@ -151,13 +148,13 @@ protected function getFileNamePropertyValue($obj, $field) )); } - $value = $mapping->getFileNameProperty()->getValue($obj); - if ($value === null) { + $name = $mapping->getFileName($obj); + if ($name === null) { throw new \InvalidArgumentException(sprintf( 'Unable to get filename property value: "%s"', $field )); } - return array($mapping, $value); + return array($mapping, $name); } } diff --git a/Storage/FileSystemStorage.php b/Storage/FileSystemStorage.php index 858772d0..dbc4fe95 100644 --- a/Storage/FileSystemStorage.php +++ b/Storage/FileSystemStorage.php @@ -51,7 +51,7 @@ protected function doResolvePath($dir, $name) */ public function resolveUri($obj, $field) { - list($mapping, $name) = $this->getFileNamePropertyValue($obj, $field); + list($mapping, $name) = $this->getFileName($obj, $field); $uriPrefix = $mapping->getUriPrefix(); $parts = explode($uriPrefix, $this->convertWindowsDirectorySeparator($mapping->getUploadDir($obj, $field))); diff --git a/composer.json b/composer.json index f8e837f5..e1d42f5b 100644 --- a/composer.json +++ b/composer.json @@ -15,6 +15,7 @@ "php": ">=5.3.2", "symfony/framework-bundle": "~2.0", "jms/metadata": "~1.5", + "symfony/property-access": "=>2.3", "symfony/finder": ">=2.0" }, "require-dev": { From ffb7ad98f5c77b9511d0535434f4976f998f0563 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Tue, 10 Dec 2013 21:04:06 +0100 Subject: [PATCH 03/54] Cleaned a bit the configuration definition --- DependencyInjection/Configuration.php | 26 ++++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index a158761c..ca8755e8 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -2,6 +2,7 @@ namespace Vich\UploaderBundle\DependencyInjection; +use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; @@ -40,6 +41,19 @@ public function getConfigTreeBuilder() ->scalarNode('storage')->defaultValue('vich_uploader.storage.file_system')->end() ->scalarNode('twig')->defaultTrue()->end() ->scalarNode('gaufrette')->defaultFalse()->end() + ->end() + ; + + $this->addMetadataSection($root); + $this->addMappingsSection($root); + + return $tb; + } + + protected function addMetadataSection(ArrayNodeDefinition $node) + { + $node + ->children() ->arrayNode('metadata') ->addDefaultsIfNotSet() ->fixXmlConfig('directory', 'directories') @@ -62,6 +76,13 @@ public function getConfigTreeBuilder() ->end() ->end() ->end() + ->end(); + } + + protected function addMappingsSection(ArrayNodeDefinition $node) + { + $node + ->children() ->arrayNode('mappings') ->useAttributeAsKey('id') ->prototype('array') @@ -76,9 +97,6 @@ public function getConfigTreeBuilder() ->end() ->end() ->end() - ->end() - ; - - return $tb; + ->end(); } } From f81d091500cc34c164dd604ab43ba8ff75c9bc08 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Tue, 10 Dec 2013 21:29:41 +0100 Subject: [PATCH 04/54] Fixed dependency constraint --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index e1d42f5b..3b1defd1 100644 --- a/composer.json +++ b/composer.json @@ -15,7 +15,7 @@ "php": ">=5.3.2", "symfony/framework-bundle": "~2.0", "jms/metadata": "~1.5", - "symfony/property-access": "=>2.3", + "symfony/property-access": ">=2.3", "symfony/finder": ">=2.0" }, "require-dev": { From 06a8dfb5fe7328dbb98ff144fc120e7f1e8aae30 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Tue, 10 Dec 2013 21:39:35 +0100 Subject: [PATCH 05/54] Fixed a few typos --- Adapter/ODM/MongoDB/MongoDBAdapter.php | 2 +- Adapter/ORM/DoctrineORMAdapter.php | 2 +- DependencyInjection/VichUploaderExtension.php | 2 +- Mapping/PropertyMappingFactory.php | 2 -- Metadata/Driver/Yaml.php | 16 ++++++++-------- Storage/AbstractStorage.php | 2 +- 6 files changed, 12 insertions(+), 14 deletions(-) diff --git a/Adapter/ODM/MongoDB/MongoDBAdapter.php b/Adapter/ODM/MongoDB/MongoDBAdapter.php index 6a5c21bd..071d9ff4 100644 --- a/Adapter/ODM/MongoDB/MongoDBAdapter.php +++ b/Adapter/ODM/MongoDB/MongoDBAdapter.php @@ -45,6 +45,6 @@ public function getReflectionClass($object) return new \ReflectionClass(get_parent_class($object)); } - return new \ReflectionClass($obj); + return new \ReflectionClass($object); } } diff --git a/Adapter/ORM/DoctrineORMAdapter.php b/Adapter/ORM/DoctrineORMAdapter.php index 8ffbd1be..3bbf3d65 100644 --- a/Adapter/ORM/DoctrineORMAdapter.php +++ b/Adapter/ORM/DoctrineORMAdapter.php @@ -45,6 +45,6 @@ public function getReflectionClass($object) return new \ReflectionClass(get_parent_class($object)); } - return new \ReflectionClass($obj); + return new \ReflectionClass($object); } } diff --git a/DependencyInjection/VichUploaderExtension.php b/DependencyInjection/VichUploaderExtension.php index 7ddd2848..d3bda03a 100644 --- a/DependencyInjection/VichUploaderExtension.php +++ b/DependencyInjection/VichUploaderExtension.php @@ -97,7 +97,7 @@ protected function registerMetadataDirectories(ContainerBuilder $container, arra // directories $directories = array(); if ($config['metadata']['auto_detection']) { - foreach ($bundles as $name => $class) { + foreach ($bundles as $class) { $ref = new \ReflectionClass($class); $directory = dirname($ref->getFileName()).'/Resources/config/vich_uploader'; diff --git a/Mapping/PropertyMappingFactory.php b/Mapping/PropertyMappingFactory.php index 0f7584a8..f26ead36 100644 --- a/Mapping/PropertyMappingFactory.php +++ b/Mapping/PropertyMappingFactory.php @@ -130,8 +130,6 @@ protected function checkUploadable(\ReflectionClass $class) */ protected function createMapping($obj, $fieldName, array $mappingData) { - $class = $this->adapter->getReflectionClass($obj); - if (!array_key_exists($mappingData['mapping'], $this->mappings)) { throw new \InvalidArgumentException(sprintf( 'No mapping named "%s" configured.', $mappingData['mapping'] diff --git a/Metadata/Driver/Yaml.php b/Metadata/Driver/Yaml.php index 380ae314..616e95c1 100644 --- a/Metadata/Driver/Yaml.php +++ b/Metadata/Driver/Yaml.php @@ -19,7 +19,7 @@ class Yaml extends AbstractFileDriver protected function loadMetadataFromFile($file, \ReflectionClass $class = null) { $config = $this->loadMappingFile($file); - $className = $this->guessClassName($config, $class); + $className = $this->guessClassName($file, $config, $class); $metadata = new ClassMetadata($className); foreach ($config[$className] as $field => $mappingData) { @@ -48,16 +48,16 @@ protected function getExtension() return 'yml'; } - protected function guessClassName(array $config, \ReflectionClass $class = null) + protected function guessClassName($file, array $config, \ReflectionClass $class = null) { - if ($class !== null) { - if (!isset($config[$class->name])) { - throw new \RuntimeException(sprintf('Expected metadata for class %s to be defined in %s.', $class->name, $file)); - } + if ($class === null) { + return current(array_keys($config)); + } - return $class->name; + if (!isset($config[$class->name])) { + throw new \RuntimeException(sprintf('Expected metadata for class %s to be defined in %s.', $class->name, $file)); } - return current(array_keys($config)); + return $class->name; } } diff --git a/Storage/AbstractStorage.php b/Storage/AbstractStorage.php index 9ac9c4e2..365a1bec 100644 --- a/Storage/AbstractStorage.php +++ b/Storage/AbstractStorage.php @@ -136,7 +136,7 @@ public function resolveUri($obj, $field) list($mapping, $filename) = $this->getFileName($obj, $field); $uriPrefix = $mapping->getUriPrefix(); - return $name ? ($uriPrefix . '/' . $filename) : ''; + return $filename ? ($uriPrefix . '/' . $filename) : ''; } protected function getFileName($obj, $field) From 8746f7430352459e628415c4c346142ef9ffcfd8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Tue, 10 Dec 2013 22:08:43 +0100 Subject: [PATCH 06/54] Added a few tests for the PropelAdapter class --- Tests/Adapter/ORM/DoctrineORMAdapterTest.php | 2 +- Tests/Adapter/Propel/PropelAdapterTest.php | 41 ++++++++++++++++++++ composer.json | 2 + 3 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 Tests/Adapter/Propel/PropelAdapterTest.php diff --git a/Tests/Adapter/ORM/DoctrineORMAdapterTest.php b/Tests/Adapter/ORM/DoctrineORMAdapterTest.php index 3dc9768c..7110d97c 100644 --- a/Tests/Adapter/ORM/DoctrineORMAdapterTest.php +++ b/Tests/Adapter/ORM/DoctrineORMAdapterTest.php @@ -16,7 +16,7 @@ class DoctrineORMAdapterTest extends \PHPUnit_Framework_TestCase /** * Test the getObjectFromEvent method. */ - public function testGetObjectFromArgs() + public function testGetObjectFromEvent() { if (!class_exists('Doctrine\ORM\Event\LifecycleEventArgs')) { $this->markTestSkipped('Doctrine\ORM\Event\LifecycleEventArgs does not exist.'); diff --git a/Tests/Adapter/Propel/PropelAdapterTest.php b/Tests/Adapter/Propel/PropelAdapterTest.php new file mode 100644 index 00000000..87305da5 --- /dev/null +++ b/Tests/Adapter/Propel/PropelAdapterTest.php @@ -0,0 +1,41 @@ + + */ +class PropelAdapterTest extends \PHPUnit_Framework_TestCase +{ + /** + * Test the getObjectFromEvent method. + */ + public function testGetObjectFromEvent() + { + $event = $this->getMock('\Symfony\Component\EventDispatcher\GenericEvent'); + $event + ->expects($this->once()) + ->method('getSubject') + ->will($this->returnValue(42)); + + $adapter = new PropelAdapter(); + $this->assertSame(42, $adapter->getObjectFromEvent($event)); + } + + /** + * Tests the getReflectionClass method. + */ + public function testGetReflectionClass() + { + $adapter = new PropelAdapter(); + + $obj = new \DateTime(); + $class = $adapter->getReflectionClass($obj); + + $this->assertSame('DateTime', $class->getName()); + } +} diff --git a/composer.json b/composer.json index 3b1defd1..57ea70cb 100644 --- a/composer.json +++ b/composer.json @@ -23,6 +23,8 @@ "doctrine/mongodb-odm": "@dev", "knplabs/knp-gaufrette-bundle": "*", "phpunit/phpunit": "~3.7", + "propel/propel1": "~1", + "willdurand/propel-eventdispatcher-bundle": "~1.0", "symfony/yaml": "@stable" }, "suggest": { From e079f406e4558173ae0cbce1513c74f23c97be21 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Tue, 10 Dec 2013 22:21:21 +0100 Subject: [PATCH 07/54] Updated FileInjectorTest --- Tests/Injector/FileInjectorTest.php | 79 ++++++++++++----------------- 1 file changed, 32 insertions(+), 47 deletions(-) diff --git a/Tests/Injector/FileInjectorTest.php b/Tests/Injector/FileInjectorTest.php index 38d8017f..2f916826 100644 --- a/Tests/Injector/FileInjectorTest.php +++ b/Tests/Injector/FileInjectorTest.php @@ -41,18 +41,12 @@ public function testInjectsOneFile() { $uploadDir = __DIR__ . '/..'; $name = 'file.txt'; + $filePropertyName = 'file'; file_put_contents(sprintf('%s/%s', $uploadDir, $name), ''); $obj = $this->getMock('Vich\UploaderBundle\Tests\DummyEntity'); - $prop = $this->getMockBuilder('\ReflectionProperty') - ->disableOriginalConstructor() - ->getMock(); - $prop - ->expects($this->once()) - ->method('setValue'); - $fileMapping = $this->getMockBuilder('Vich\UploaderBundle\Mapping\PropertyMapping') ->disableOriginalConstructor() ->getMock(); @@ -61,9 +55,15 @@ public function testInjectsOneFile() ->method('getInjectOnLoad') ->will($this->returnValue(true)); $fileMapping - ->expects($this->exactly(2)) - ->method('getProperty') - ->will($this->returnValue($prop)); + ->expects($this->exactly(1)) + ->method('getFilePropertyName') + ->will($this->returnValue($filePropertyName)); + $fileMapping + ->expects($this->exactly(1)) + ->method('setFile') + ->with($this->equalTo($obj), $this->callback(function($file) { + return $file instanceof \Symfony\Component\HttpFoundation\File\File; + })); $this->factory ->expects($this->once()) @@ -74,6 +74,7 @@ public function testInjectsOneFile() $this->storage ->expects($this->once()) ->method('resolvePath') + ->with($this->equalTo($obj), $this->equalTo($filePropertyName)) ->will($this->returnValue($uploadDir)); $inject = new FileInjector($this->factory, $this->storage); @@ -96,20 +97,6 @@ public function testInjectTwoFiles() $obj = $this->getMock('Vich\UploaderBundle\Tests\TwoFieldsDummyEntity'); - $fileProp = $this->getMockBuilder('\ReflectionProperty') - ->disableOriginalConstructor() - ->getMock(); - $fileProp - ->expects($this->once()) - ->method('setValue'); - - $imageProp = $this->getMockBuilder('\ReflectionProperty') - ->disableOriginalConstructor() - ->getMock(); - $imageProp - ->expects($this->once()) - ->method('setValue'); - $fileMapping = $this->getMockBuilder('Vich\UploaderBundle\Mapping\PropertyMapping') ->disableOriginalConstructor() ->getMock(); @@ -118,9 +105,15 @@ public function testInjectTwoFiles() ->method('getInjectOnLoad') ->will($this->returnValue(true)); $fileMapping - ->expects($this->exactly(2)) - ->method('getProperty') - ->will($this->returnValue($fileProp)); + ->expects($this->exactly(1)) + ->method('getFilePropertyName') + ->will($this->returnValue('file')); + $fileMapping + ->expects($this->exactly(1)) + ->method('setFile') + ->with($this->equalTo($obj), $this->callback(function($file) { + return $file instanceof \Symfony\Component\HttpFoundation\File\File; + })); $imageMapping = $this->getMockBuilder('Vich\UploaderBundle\Mapping\PropertyMapping') ->disableOriginalConstructor() @@ -130,9 +123,15 @@ public function testInjectTwoFiles() ->method('getInjectOnLoad') ->will($this->returnValue(true)); $imageMapping - ->expects($this->exactly(2)) - ->method('getProperty') - ->will($this->returnValue($imageProp)); + ->expects($this->exactly(1)) + ->method('getFilePropertyName') + ->will($this->returnValue('image')); + $imageMapping + ->expects($this->exactly(1)) + ->method('setFile') + ->with($this->equalTo($obj), $this->callback(function($file) { + return $file instanceof \Symfony\Component\HttpFoundation\File\File; + })); $this->factory ->expects($this->once()) @@ -199,24 +198,10 @@ public function testPropertyIsNullWhenFileNamePropertyIsNull() ->expects($this->once()) ->method('getInjectOnLoad') ->will($this->returnValue(true)); - - $prop = $this->getMockBuilder('\ReflectionProperty') - ->disableOriginalConstructor() - ->getMock(); - - $prop - ->expects($this->once()) - ->method('getName') - ->will($this->returnValue('test_adapter')); - - $prop - ->expects($this->once()) - ->method('setValue'); - $fileMapping - ->expects($this->exactly(2)) - ->method('getProperty') - ->will($this->returnValue($prop)); + ->expects($this->exactly(1)) + ->method('getFilePropertyName') + ->will($this->returnValue('file')); $this->factory ->expects($this->once()) From c95e9e1e201fbe956def5221a60b645554fdaeba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Tue, 10 Dec 2013 22:23:20 +0100 Subject: [PATCH 08/54] Updated PropertyMapping tests --- ...roperyMappingTest.php => PropertyMappingTest.php} | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) rename Tests/Mapping/{ProperyMappingTest.php => PropertyMappingTest.php} (65%) diff --git a/Tests/Mapping/ProperyMappingTest.php b/Tests/Mapping/PropertyMappingTest.php similarity index 65% rename from Tests/Mapping/ProperyMappingTest.php rename to Tests/Mapping/PropertyMappingTest.php index a9ad0e60..dc7bb559 100644 --- a/Tests/Mapping/ProperyMappingTest.php +++ b/Tests/Mapping/PropertyMappingTest.php @@ -17,15 +17,15 @@ class PropertyMappingTest extends \PHPUnit_Framework_TestCase */ public function testConfiguredMappingAccess() { - $prop = new PropertyMapping(); + $prop = new PropertyMapping('file', 'fileName'); $prop->setMapping(array( - 'delete_on_remove' => true, - 'delete_on_update' => true, - 'upload_destination' => '/tmp', - 'inject_on_load' => true + 'delete_on_remove' => true, + 'delete_on_update' => true, + 'upload_destination' => '/tmp', + 'inject_on_load' => true )); - $this->assertEquals($prop->getUploadDir(), '/tmp'); + $this->assertEquals('/tmp', $prop->getUploadDir()); $this->assertTrue($prop->getDeleteOnRemove()); $this->assertTrue($prop->getInjectOnLoad()); } From 88b23bc2091eba260d6fd1345e4f3b72e271c131 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Tue, 10 Dec 2013 22:31:47 +0100 Subject: [PATCH 09/54] Updated DoctrineUploaderListener tests --- ...t.php => DoctrineUploaderListenerTest.php} | 106 ++++++------------ 1 file changed, 35 insertions(+), 71 deletions(-) rename Tests/EventListener/{UploaderListenerTest.php => DoctrineUploaderListenerTest.php} (76%) diff --git a/Tests/EventListener/UploaderListenerTest.php b/Tests/EventListener/DoctrineUploaderListenerTest.php similarity index 76% rename from Tests/EventListener/UploaderListenerTest.php rename to Tests/EventListener/DoctrineUploaderListenerTest.php index 3493d639..9b37f909 100644 --- a/Tests/EventListener/UploaderListenerTest.php +++ b/Tests/EventListener/DoctrineUploaderListenerTest.php @@ -2,15 +2,15 @@ namespace Vich\UploaderBundle\Tests\EventListener; -use Vich\UploaderBundle\EventListener\UploaderListener; +use Vich\UploaderBundle\EventListener\DoctrineUploaderListener; use Vich\UploaderBundle\Tests\DummyEntity; /** - * UploaderListenerTest. + * DoctrineUploaderListenerTest. * * @author Dustin Dobervich */ -class UploaderListenerTest extends \PHPUnit_Framework_TestCase +class DoctrineUploaderListenerTest extends \PHPUnit_Framework_TestCase { /** * @var \Vich\UploaderBundle\Adapter\AdapterInterface $adapter @@ -23,14 +23,9 @@ class UploaderListenerTest extends \PHPUnit_Framework_TestCase protected $mapping; /** - * @var \Vich\UploaderBundle\Storage\StorageInterface $storage + * @var \Vich\UploaderBundle\Handler\UploadHandler $handler */ - protected $storage; - - /** - * @var \Vich\UploaderBundle\Injector\FileInjectorInterface $injector - */ - protected $injector; + protected $handler; /** * Sets up the test @@ -39,8 +34,7 @@ public function setUp() { $this->adapter = $this->getAdapterMock(); $this->mapping = $this->getMappingMock(); - $this->storage = $this->getStorageMock(); - $this->injector = $this->getInjectorMock(); + $this->handler = $this->getHandlerMock(); } /** @@ -48,7 +42,7 @@ public function setUp() */ public function testGetSubscribedEvents() { - $listener = new UploaderListener($this->adapter, $this->mapping, $this->storage, $this->injector); + $listener = new DoctrineUploaderListener($this->adapter, $this->mapping, $this->handler); $events = $listener->getSubscribedEvents(); $this->assertTrue(in_array('prePersist', $events)); @@ -85,17 +79,12 @@ public function testPrePersist() ->with($class) ->will($this->returnValue(true)); - $this->storage - ->expects($this->once()) - ->method('upload') - ->with($obj); - - $this->injector + $this->handler ->expects($this->once()) - ->method('injectFiles') + ->method('handleUpload') ->with($obj); - $listener = new UploaderListener($this->adapter, $this->mapping, $this->storage, $this->injector); + $listener = new DoctrineUploaderListener($this->adapter, $this->mapping, $this->handler); $listener->prePersist($args); } @@ -127,15 +116,11 @@ public function testPrePersistSkipsNonUploadable() ->with($class) ->will($this->returnValue(false)); - $this->storage + $this->handler ->expects($this->never()) - ->method('upload'); + ->method('handleUpload'); - $this->injector - ->expects($this->never()) - ->method('injectFiles'); - - $listener = new UploaderListener($this->adapter, $this->mapping, $this->storage, $this->injector); + $listener = new DoctrineUploaderListener($this->adapter, $this->mapping, $this->handler); $listener->prePersist($args); } @@ -172,17 +157,12 @@ public function testPreUpdate() ->with($class) ->will($this->returnValue(true)); - $this->storage - ->expects($this->once()) - ->method('upload') - ->with($obj); - - $this->injector + $this->handler ->expects($this->once()) - ->method('injectFiles') + ->method('handleUpload') ->with($obj); - $listener = new UploaderListener($this->adapter, $this->mapping, $this->storage, $this->injector); + $listener = new DoctrineUploaderListener($this->adapter, $this->mapping, $this->handler); $listener->preUpdate($args); } @@ -214,19 +194,15 @@ public function testPreUpdateSkipsNonUploadable() ->with($class) ->will($this->returnValue(false)); - $this->storage - ->expects($this->never()) - ->method('upload'); - $this->adapter ->expects($this->never()) ->method('recomputeChangeSet'); - $this->injector + $this->handler ->expects($this->never()) - ->method('injectFiles'); + ->method('handleUpload'); - $listener = new UploaderListener($this->adapter, $this->mapping, $this->storage, $this->injector); + $listener = new DoctrineUploaderListener($this->adapter, $this->mapping, $this->handler); $listener->preUpdate($args); } @@ -258,12 +234,12 @@ public function testPostLoad() ->with($class) ->will($this->returnValue(true)); - $this->injector + $this->handler ->expects($this->once()) - ->method('injectFiles') + ->method('handleHydration') ->with($obj); - $listener = new UploaderListener($this->adapter, $this->mapping, $this->storage, $this->injector); + $listener = new DoctrineUploaderListener($this->adapter, $this->mapping, $this->handler); $listener->postLoad($args); } @@ -295,11 +271,11 @@ public function testPostLoadSkipsNonUploadable() ->with($class) ->will($this->returnValue(false)); - $this->injector + $this->handler ->expects($this->never()) - ->method('injectFiles'); + ->method('handleHydration'); - $listener = new UploaderListener($this->adapter, $this->mapping, $this->storage, $this->injector); + $listener = new DoctrineUploaderListener($this->adapter, $this->mapping, $this->handler); $listener->postLoad($args); } @@ -331,12 +307,12 @@ public function testPostRemove() ->with($class) ->will($this->returnValue(true)); - $this->storage + $this->handler ->expects($this->once()) - ->method('remove') + ->method('handleDeletion') ->with($obj); - $listener = new UploaderListener($this->adapter, $this->mapping, $this->storage, $this->injector); + $listener = new DoctrineUploaderListener($this->adapter, $this->mapping, $this->handler); $listener->postRemove($args); } @@ -368,11 +344,11 @@ public function testPostRemoveSkipsNonUploadable() ->with($class) ->will($this->returnValue(false)); - $this->storage + $this->handler ->expects($this->never()) - ->method('remove'); + ->method('handleDeletion'); - $listener = new UploaderListener($this->adapter, $this->mapping, $this->storage, $this->injector); + $listener = new DoctrineUploaderListener($this->adapter, $this->mapping, $this->handler); $listener->postRemove($args); } @@ -401,25 +377,13 @@ protected function getMappingMock() } /** - * Creates a mock storage. - * - * @return \Vich\UploaderBundle\Storage\StorageInterface The mock storage. - */ - protected function getStorageMock() - { - return $this->getMockBuilder('Vich\UploaderBundle\Storage\StorageInterface') - ->disableOriginalConstructor() - ->getMock(); - } - - /** - * Creates a mock injector. + * Creates a mock handler. * - * @return \Vich\UploaderBundle\Injector\FileInjectorInterface The mock injector. + * @return \Vich\UploaderBundle\Handler\UploadHandler The handler mock. */ - protected function getInjectorMock() + protected function getHandlerMock() { - return $this->getMockBuilder('Vich\UploaderBundle\Injector\FileInjectorInterface') + return $this->getMockBuilder('Vich\UploaderBundle\Handler\UploadHandler') ->disableOriginalConstructor() ->getMock(); } From 5a52771b094955350079dd55a5845915023bd2a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Tue, 10 Dec 2013 22:48:55 +0100 Subject: [PATCH 10/54] Updated Tests/Storage/FileSystemStorageTest.php --- Tests/Storage/FileSystemStorageTest.php | 170 ++++++------------------ 1 file changed, 44 insertions(+), 126 deletions(-) diff --git a/Tests/Storage/FileSystemStorageTest.php b/Tests/Storage/FileSystemStorageTest.php index be7a94d6..2aadcd93 100644 --- a/Tests/Storage/FileSystemStorageTest.php +++ b/Tests/Storage/FileSystemStorageTest.php @@ -33,11 +33,10 @@ public function testUploadSkipsMappingOnNullFile() { $obj = new DummyEntity(); - $mapping = $this->getMock('Vich\UploaderBundle\Mapping\PropertyMapping'); - + $mapping = $this->getMappingMock(); $mapping ->expects($this->once()) - ->method('getPropertyValue') + ->method('getFile') ->will($this->returnValue(null)); $mapping @@ -47,10 +46,9 @@ public function testUploadSkipsMappingOnNullFile() $mapping ->expects($this->never()) ->method('getNamer'); - $mapping ->expects($this->never()) - ->method('getFileNameProperty'); + ->method('getFileName'); $this->factory ->expects($this->once()) @@ -70,7 +68,7 @@ public function testUploadSkipsMappingOnNonUploadedFileInstance() { $obj = new DummyEntity(); - $mapping = $this->getMock('Vich\UploaderBundle\Mapping\PropertyMapping'); + $mapping = $this->getMappingMock(); $file = $this->getMockBuilder('Symfony\Component\HttpFoundation\File\File') ->disableOriginalConstructor() @@ -78,7 +76,7 @@ public function testUploadSkipsMappingOnNonUploadedFileInstance() $mapping ->expects($this->once()) - ->method('getPropertyValue') + ->method('getFile') ->will($this->returnValue($file)); $mapping @@ -91,7 +89,7 @@ public function testUploadSkipsMappingOnNonUploadedFileInstance() $mapping ->expects($this->never()) - ->method('getFileNameProperty'); + ->method('getFileName'); $this->factory ->expects($this->once()) @@ -111,8 +109,7 @@ public function testRemoveSkipsConfiguredNotToDeleteOnRemove() { $obj = new DummyEntity(); - $mapping = $this->getMock('Vich\UploaderBundle\Mapping\PropertyMapping'); - + $mapping = $this->getMappingMock(); $mapping ->expects($this->once()) ->method('getDeleteOnRemove') @@ -120,7 +117,7 @@ public function testRemoveSkipsConfiguredNotToDeleteOnRemove() $mapping ->expects($this->never()) - ->method('getFileNameProperty'); + ->method('getFileName'); $this->factory ->expects($this->once()) @@ -140,16 +137,7 @@ public function testRemoveSkipsNullFileNameProperty() { $obj = new DummyEntity(); - $prop = $this->getMockBuilder('\ReflectionProperty') - ->disableOriginalConstructor() - ->getMock(); - $prop - ->expects($this->once()) - ->method('getValue') - ->with($obj) - ->will($this->returnValue(null)); - - $mapping = $this->getMock('Vich\UploaderBundle\Mapping\PropertyMapping'); + $mapping = $this->getMappingMock(); $mapping ->expects($this->once()) ->method('getDeleteOnRemove') @@ -157,8 +145,8 @@ public function testRemoveSkipsNullFileNameProperty() $mapping ->expects($this->once()) - ->method('getFileNameProperty') - ->will($this->returnValue($prop)); + ->method('getFileName') + ->will($this->returnValue(null)); $mapping ->expects($this->never()) @@ -173,6 +161,7 @@ public function testRemoveSkipsNullFileNameProperty() $storage = new FileSystemStorage($this->factory); $storage->remove($obj); } + /** * Test the remove method skips trying to remove a file that no longer exists */ @@ -180,25 +169,7 @@ public function testRemoveSkipsNonExistingFile() { $obj = new DummyEntity(); - $prop = $this->getMockBuilder('\ReflectionProperty') - ->disableOriginalConstructor() - ->getMock(); - $prop - ->expects($this->once()) - ->method('getValue') - ->with($obj) - ->will($this->returnValue('file.txt')); - - $propertyMock = $this->getMockBuilder('\ReflectionProperty') - ->disableOriginalConstructor() - ->getMock(); - - $propertyMock - ->expects($this->any()) - ->method('getName') - ->will($this->returnValue(null)); - - $mapping = $this->getMock('Vich\UploaderBundle\Mapping\PropertyMapping'); + $mapping = $this->getMappingMock(); $mapping ->expects($this->once()) ->method('getDeleteOnRemove') @@ -209,15 +180,10 @@ public function testRemoveSkipsNonExistingFile() ->method('getUploadDir') ->will($this->returnValue('/tmp')); - $mapping - ->expects($this->any()) - ->method('getProperty') - ->will($this->returnValue($propertyMock)); - $mapping ->expects($this->once()) - ->method('getFileNameProperty') - ->will($this->returnValue($prop)); + ->method('getFileName') + ->will($this->returnValue('file.txt')); $this->factory ->expects($this->once()) @@ -240,26 +206,15 @@ public function testResolvePath() { $obj = new DummyEntity(); - $mapping = $this->getMock('Vich\UploaderBundle\Mapping\PropertyMapping'); - - $prop = $this->getMockBuilder('\ReflectionProperty') - ->disableOriginalConstructor() - ->getMock(); - $prop - ->expects($this->once()) - ->method('getValue') - ->with($obj) - ->will($this->returnValue('file.txt')); - + $mapping = $this->getMappingMock(); $mapping - ->expects($this->once()) - ->method('getUploadDir') - ->will($this->returnValue('/tmp')); - + ->expects($this->once()) + ->method('getUploadDir') + ->will($this->returnValue('/tmp')); $mapping - ->expects($this->once()) - ->method('getFileNameProperty') - ->will($this->returnValue($prop)); + ->expects($this->once()) + ->method('getFileName') + ->will($this->returnValue('file.txt')); $this->factory ->expects($this->once()) @@ -282,17 +237,7 @@ public function testResolveUri($uploadDir, $uri) { $obj = new DummyEntity(); - $mapping = $this->getMock('Vich\UploaderBundle\Mapping\PropertyMapping'); - - $prop = $this->getMockBuilder('\ReflectionProperty') - ->disableOriginalConstructor() - ->getMock(); - $prop - ->expects($this->once()) - ->method('getValue') - ->with($obj) - ->will($this->returnValue('file.txt')); - + $mapping = $this->getMappingMock(); $mapping ->expects($this->once()) ->method('getUploadDir') @@ -305,8 +250,8 @@ public function testResolveUri($uploadDir, $uri) $mapping ->expects($this->once()) - ->method('getFileNameProperty') - ->will($this->returnValue($prop)); + ->method('getFileName') + ->will($this->returnValue('file.txt')); $this->factory ->expects($this->once()) @@ -372,41 +317,24 @@ public function testUploadedFileIsCorrectlyMoved() $file = $this->getMockBuilder('Symfony\Component\HttpFoundation\File\UploadedFile') ->disableOriginalConstructor() ->getMock(); - $file ->expects($this->any()) ->method('getClientOriginalName') ->will($this->returnValue('filename.txt')); - $prop = $this->getMockBuilder('\ReflectionProperty') - ->disableOriginalConstructor() - ->getMock(); - - $name = new \stdClass(); - - $prop - ->expects($this->any()) - ->method('getName') - ->will($this->returnValue($name)); - - $mapping = $this->getMock('Vich\UploaderBundle\Mapping\PropertyMapping'); - - $mapping - ->expects($this->any()) - ->method('getProperty') - ->will($this->returnValue($prop)); - - $mapping - ->expects($this->once()) - ->method('getFileNameProperty') - ->will($this->returnValue($prop)); + $mapping = $this->getMappingMock(); $mapping ->expects($this->once()) - ->method('getPropertyValue') + ->method('getFile') ->with($obj) ->will($this->returnValue($file)); + $mapping + ->expects($this->any()) + ->method('getFilePropertyName') + ->will($this->returnValue('file')); + $mapping ->expects($this->once()) ->method('getDeleteOnUpdate') @@ -420,7 +348,7 @@ public function testUploadedFileIsCorrectlyMoved() $mapping ->expects($this->once()) ->method('getUploadDir') - ->with($obj,$name) + ->with($obj, 'file') ->will($this->returnValue('/dir')); $this->factory @@ -446,33 +374,22 @@ public function testUploadedFileIsCorrectlyMoved() public function testFilenameWithDirectoriesIsUploadedToCorrectDirectory($dir, $filename, $expectedDir, $expectedFileName) { $obj = new DummyEntity(); + $name = 'lala'; $file = $this->getMockBuilder('Symfony\Component\HttpFoundation\File\UploadedFile') ->disableOriginalConstructor() ->getMock(); - $prop = $this->getMockBuilder('\ReflectionProperty') - ->disableOriginalConstructor() - ->getMock(); - - $name = new \stdClass(); - $namer = $this->getMockBuilder('Vich\UploaderBundle\Naming\NamerInterface') ->disableOriginalConstructor() ->getMock(); - $namer ->expects($this->once()) ->method('name') ->with($obj, $name) ->will($this->returnValue($filename)); - $prop - ->expects($this->any()) - ->method('getName') - ->will($this->returnValue($name)); - - $mapping = $this->getMock('Vich\UploaderBundle\Mapping\PropertyMapping'); + $mapping = $this->getMappingMock(); $mapping ->expects($this->once()) @@ -481,17 +398,12 @@ public function testFilenameWithDirectoriesIsUploadedToCorrectDirectory($dir, $f $mapping ->expects($this->any()) - ->method('getProperty') - ->will($this->returnValue($prop)); - - $mapping - ->expects($this->once()) - ->method('getFileNameProperty') - ->will($this->returnValue($prop)); + ->method('getFilePropertyName') + ->will($this->returnValue($name)); $mapping ->expects($this->once()) - ->method('getPropertyValue') + ->method('getFile') ->with($obj) ->will($this->returnValue($file)); @@ -557,4 +469,10 @@ protected function getFactoryMock() ->getMock(); } + protected function getMappingMock() + { + return $this->getMockBuilder('Vich\UploaderBundle\Mapping\PropertyMapping') + ->disableOriginalConstructor() + ->getMock(); + } } From 9355d1036d78f18dfee42b5945ba2c608094b519 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Tue, 10 Dec 2013 23:01:54 +0100 Subject: [PATCH 11/54] Fixed GaufretteStorage test --- Tests/Storage/GaufretteStorageTest.php | 172 +++++-------------------- 1 file changed, 33 insertions(+), 139 deletions(-) diff --git a/Tests/Storage/GaufretteStorageTest.php b/Tests/Storage/GaufretteStorageTest.php index 99602aaa..3dc0e09b 100644 --- a/Tests/Storage/GaufretteStorageTest.php +++ b/Tests/Storage/GaufretteStorageTest.php @@ -40,11 +40,10 @@ public function testUploadSkipsMappingOnNullFile() { $obj = new DummyEntity(); - $mapping = $this->getMock('Vich\UploaderBundle\Mapping\PropertyMapping'); - + $mapping = $this->getMappingMock(); $mapping ->expects($this->once()) - ->method('getPropertyValue') + ->method('getFile') ->will($this->returnValue(null)); $mapping @@ -55,10 +54,6 @@ public function testUploadSkipsMappingOnNullFile() ->expects($this->never()) ->method('getNamer'); - $mapping - ->expects($this->never()) - ->method('getFileNameProperty'); - $this->factory ->expects($this->once()) ->method('fromObject') @@ -77,7 +72,7 @@ public function testUploadSkipsMappingOnNonUploadedFileInstance() { $obj = new DummyEntity(); - $mapping = $this->getMock('Vich\UploaderBundle\Mapping\PropertyMapping'); + $mapping = $this->getMappingMock(); $file = $this->getMockBuilder('Symfony\Component\HttpFoundation\File\File') ->disableOriginalConstructor() @@ -85,7 +80,7 @@ public function testUploadSkipsMappingOnNonUploadedFileInstance() $mapping ->expects($this->once()) - ->method('getPropertyValue') + ->method('getFile') ->will($this->returnValue($file)); $mapping @@ -96,10 +91,6 @@ public function testUploadSkipsMappingOnNonUploadedFileInstance() ->expects($this->never()) ->method('getNamer'); - $mapping - ->expects($this->never()) - ->method('getFileNameProperty'); - $this->factory ->expects($this->once()) ->method('fromObject') @@ -118,16 +109,14 @@ public function testRemoveSkipsConfiguredNotToDeleteOnRemove() { $obj = new DummyEntity(); - $mapping = $this->getMock('Vich\UploaderBundle\Mapping\PropertyMapping'); - + $mapping = $this->getMappingMock(); $mapping ->expects($this->once()) ->method('getDeleteOnRemove') ->will($this->returnValue(false)); - $mapping ->expects($this->never()) - ->method('getFileNameProperty'); + ->method('getFileName'); $this->factory ->expects($this->once()) @@ -147,16 +136,7 @@ public function testRemoveSkipsNullFileNameProperty() { $obj = new DummyEntity(); - $prop = $this->getMockBuilder('\ReflectionProperty') - ->disableOriginalConstructor() - ->getMock(); - $prop - ->expects($this->once()) - ->method('getValue') - ->with($obj) - ->will($this->returnValue(null)); - - $mapping = $this->getMock('Vich\UploaderBundle\Mapping\PropertyMapping'); + $mapping = $this->getMappingMock(); $mapping ->expects($this->once()) ->method('getDeleteOnRemove') @@ -164,8 +144,8 @@ public function testRemoveSkipsNullFileNameProperty() $mapping ->expects($this->once()) - ->method('getFileNameProperty') - ->will($this->returnValue($prop)); + ->method('getFileName') + ->will($this->returnValue(null)); $mapping ->expects($this->never()) @@ -188,16 +168,7 @@ public function testResolvePath() { $obj = new DummyEntity(); - $mapping = $this->getMock('Vich\UploaderBundle\Mapping\PropertyMapping'); - - $prop = $this->getMockBuilder('\ReflectionProperty') - ->disableOriginalConstructor() - ->getMock(); - $prop - ->expects($this->once()) - ->method('getValue') - ->with($obj) - ->will($this->returnValue('file.txt')); + $mapping = $this->getMappingMock(); $mapping ->expects($this->once()) @@ -206,8 +177,8 @@ public function testResolvePath() $mapping ->expects($this->once()) - ->method('getFileNameProperty') - ->will($this->returnValue($prop)); + ->method('getFileName') + ->will($this->returnValue('file.txt')); $this->factory ->expects($this->once()) @@ -266,22 +237,9 @@ public function testResolvePathWithChangedProtocol() */ public function testThatRemoveMethodDoesDeleteFile() { - $mapping = $this->getMock('Vich\UploaderBundle\Mapping\PropertyMapping'); + $mapping = $this->getMappingMock(); $obj = new DummyEntity(); - $prop = $this->getMockBuilder('\ReflectionProperty') - ->disableOriginalConstructor() - ->getMock(); - $prop - ->expects($this->any()) - ->method('getValue') - ->with($obj) - ->will($this->returnValue('file.txt')); - $prop - ->expects($this->any()) - ->method('getName') - ->will($this->returnValue('nameProperty')); - $mapping ->expects($this->once()) ->method('getDeleteOnRemove') @@ -292,12 +250,8 @@ public function testThatRemoveMethodDoesDeleteFile() ->will($this->returnValue('filesystemKey')); $mapping ->expects($this->once()) - ->method('getFileNameProperty') - ->will($this->returnValue($prop)); - $mapping - ->expects($this->once()) - ->method('getProperty') - ->will($this->returnValue($prop)); + ->method('getFileName') + ->will($this->returnValue('file.txt')); $filesystem = $this->getFilesystemMock(); $filesystem @@ -320,7 +274,7 @@ public function testThatRemoveMethodDoesDeleteFile() ->will($this->returnValue(array($mapping))); $storage = new GaufretteStorage($this->factory, $this->filesystemMap); - $storage->remove($obj, 'file'); + $storage->remove($obj); } /** @@ -328,22 +282,9 @@ public function testThatRemoveMethodDoesDeleteFile() */ public function testRemoveNotFoundFile() { - $mapping = $this->getMock('Vich\UploaderBundle\Mapping\PropertyMapping'); + $mapping = $this->getMappingMock(); $obj = new DummyEntity(); - $prop = $this->getMockBuilder('\ReflectionProperty') - ->disableOriginalConstructor() - ->getMock(); - $prop - ->expects($this->any()) - ->method('getValue') - ->with($obj) - ->will($this->returnValue('file.txt')); - $prop - ->expects($this->any()) - ->method('getName') - ->will($this->returnValue('nameProperty')); - $mapping ->expects($this->once()) ->method('getDeleteOnRemove') @@ -354,12 +295,12 @@ public function testRemoveNotFoundFile() ->will($this->returnValue('filesystemKey')); $mapping ->expects($this->once()) - ->method('getFileNameProperty') - ->will($this->returnValue($prop)); + ->method('getFileName') + ->will($this->returnValue('file.txt')); $mapping ->expects($this->once()) - ->method('getProperty') - ->will($this->returnValue($prop)); + ->method('getFilePropertyName') + ->will($this->returnValue('propertyName')); $filesystem = $this->getFilesystemMock(); $filesystem @@ -383,7 +324,7 @@ public function testRemoveNotFoundFile() ->will($this->returnValue(array($mapping))); $storage = new GaufretteStorage($this->factory, $this->filesystemMap); - $storage->remove($obj, 'file'); + $storage->remove($obj); } /** @@ -410,37 +351,20 @@ public function testUploadSetsMetadataWhenUsingMetadataSupporterAdapter() { $obj = new DummyEntity(); - $mapping = $this->getMock('Vich\UploaderBundle\Mapping\PropertyMapping'); + $mapping = $this->getMappingMock(); $adapter = $this->getMockBuilder('\Gaufrette\Adapter\MetadataSupporter') ->disableOriginalConstructor() ->setMethods(array('setMetadata', 'getMetadata')) ->getMock(); - $prop = $this->getMockBuilder('\ReflectionProperty') - ->disableOriginalConstructor() - ->getMock(); - - $prop - ->expects($this->any()) - ->method('getValue') - ->with($obj) - ->will($this->returnValue('file.txt')); - - $prop - ->expects($this->any()) - ->method('getName') - ->will($this->returnValue('nameProperty')); - $file = $this->getMockBuilder('Symfony\Component\HttpFoundation\File\UploadedFile') ->disableOriginalConstructor() ->getMock(); - $file ->expects($this->once()) ->method('getClientOriginalName') ->will($this->returnValue('filename')); - $file ->expects($this->once()) ->method('getPathname') @@ -448,7 +372,7 @@ public function testUploadSetsMetadataWhenUsingMetadataSupporterAdapter() $mapping ->expects($this->once()) - ->method('getPropertyValue') + ->method('getFile') ->will($this->returnValue($file)); $mapping @@ -456,16 +380,6 @@ public function testUploadSetsMetadataWhenUsingMetadataSupporterAdapter() ->method('getUploadDir') ->will($this->returnValue('filesystemKey')); - $mapping - ->expects($this->once()) - ->method('getFileNameProperty') - ->will($this->returnValue($prop)); - - $mapping - ->expects($this->once()) - ->method('getProperty') - ->will($this->returnValue($prop)); - $filesystem = $this ->getMockBuilder('\Gaufrette\Filesystem') ->disableOriginalConstructor() @@ -534,36 +448,19 @@ public function testUploadDoesNotSetMetadataWhenUsingNonMetadataSupporterAdapter { $obj = new DummyEntity(); - $mapping = $this->getMock('Vich\UploaderBundle\Mapping\PropertyMapping'); + $mapping = $this->getMappingMock(); $adapter = $this->getMockBuilder('\Gaufrette\Adapter\Apc') ->disableOriginalConstructor() ->getMock(); - $prop = $this->getMockBuilder('\ReflectionProperty') - ->disableOriginalConstructor() - ->getMock(); - - $prop - ->expects($this->any()) - ->method('getValue') - ->with($obj) - ->will($this->returnValue('file.txt')); - - $prop - ->expects($this->any()) - ->method('getName') - ->will($this->returnValue('nameProperty')); - $file = $this->getMockBuilder('Symfony\Component\HttpFoundation\File\UploadedFile') ->disableOriginalConstructor() ->getMock(); - $file ->expects($this->once()) ->method('getClientOriginalName') ->will($this->returnValue('filename')); - $file ->expects($this->once()) ->method('getPathname') @@ -571,7 +468,7 @@ public function testUploadDoesNotSetMetadataWhenUsingNonMetadataSupporterAdapter $mapping ->expects($this->once()) - ->method('getPropertyValue') + ->method('getFile') ->will($this->returnValue($file)); $mapping @@ -579,16 +476,6 @@ public function testUploadDoesNotSetMetadataWhenUsingNonMetadataSupporterAdapter ->method('getUploadDir') ->will($this->returnValue('filesystemKey')); - $mapping - ->expects($this->once()) - ->method('getFileNameProperty') - ->will($this->returnValue($prop)); - - $mapping - ->expects($this->once()) - ->method('getProperty') - ->will($this->returnValue($prop)); - $filesystem = $this ->getMockBuilder('\Gaufrette\Filesystem') ->disableOriginalConstructor() @@ -691,4 +578,11 @@ protected function getFilesystemMock() ->disableOriginalConstructor() ->getMock(); } + + protected function getMappingMock() + { + return $this->getMockBuilder('Vich\UploaderBundle\Mapping\PropertyMapping') + ->disableOriginalConstructor() + ->getMock(); + } } From 6db07b52e0f20472bfc998be51e9f8bb659dabb4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Tue, 10 Dec 2013 23:02:23 +0100 Subject: [PATCH 12/54] Little cs fix --- Tests/Injector/FileInjectorTest.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Tests/Injector/FileInjectorTest.php b/Tests/Injector/FileInjectorTest.php index 2f916826..dc928661 100644 --- a/Tests/Injector/FileInjectorTest.php +++ b/Tests/Injector/FileInjectorTest.php @@ -61,7 +61,7 @@ public function testInjectsOneFile() $fileMapping ->expects($this->exactly(1)) ->method('setFile') - ->with($this->equalTo($obj), $this->callback(function($file) { + ->with($this->equalTo($obj), $this->callback(function ($file) { return $file instanceof \Symfony\Component\HttpFoundation\File\File; })); @@ -111,7 +111,7 @@ public function testInjectTwoFiles() $fileMapping ->expects($this->exactly(1)) ->method('setFile') - ->with($this->equalTo($obj), $this->callback(function($file) { + ->with($this->equalTo($obj), $this->callback(function ($file) { return $file instanceof \Symfony\Component\HttpFoundation\File\File; })); @@ -129,7 +129,7 @@ public function testInjectTwoFiles() $imageMapping ->expects($this->exactly(1)) ->method('setFile') - ->with($this->equalTo($obj), $this->callback(function($file) { + ->with($this->equalTo($obj), $this->callback(function ($file) { return $file instanceof \Symfony\Component\HttpFoundation\File\File; })); From 8f99e2634050d2ab44074f19b33f16342fa90373 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Wed, 11 Dec 2013 15:49:11 +0100 Subject: [PATCH 13/54] Renamed MappingReader to MetadataReader --- EventListener/DoctrineUploaderListener.php | 20 ++++---- Mapping/PropertyMappingFactory.php | 18 +++---- .../MetadataReader.php | 19 +++++--- Resources/config/factory.xml | 2 +- Resources/config/mapping.xml | 2 +- .../DoctrineUploaderListenerTest.php | 48 +++++++++---------- Tests/Mapping/PropertyMappingFactoryTest.php | 44 ++++++++--------- 7 files changed, 79 insertions(+), 74 deletions(-) rename Mapping/MappingReader.php => Metadata/MetadataReader.php (79%) diff --git a/EventListener/DoctrineUploaderListener.php b/EventListener/DoctrineUploaderListener.php index 41292a91..68e0f4cc 100644 --- a/EventListener/DoctrineUploaderListener.php +++ b/EventListener/DoctrineUploaderListener.php @@ -7,7 +7,7 @@ use Vich\UploaderBundle\Adapter\AdapterInterface; use Vich\UploaderBundle\Handler\UploadHandler; -use Vich\UploaderBundle\Mapping\MappingReader; +use Vich\UploaderBundle\Metadata\MetadataReader; /** * DoctrineUploaderListener. @@ -22,9 +22,9 @@ class DoctrineUploaderListener implements EventSubscriber protected $adapter; /** - * @var MappingReader $mapping + * @var MetadataReader $metadata */ - protected $mapping; + protected $metadata; /** * @var UploaderHandler $handler @@ -35,13 +35,13 @@ class DoctrineUploaderListener implements EventSubscriber * Constructs a new instance of UploaderListener. * * @param AdapterInterface $adapter The adapter. - * @param MappingReader $mapping The mapping reader. + * @param MetadataReader $metadata The metadata reader. * @param UploaderHandler $handler The upload handler. */ - public function __construct(AdapterInterface $adapter, MappingReader $mapping, UploadHandler $handler) + public function __construct(AdapterInterface $adapter, MetadataReader $metadata, UploadHandler $handler) { $this->adapter = $adapter; - $this->mapping = $mapping; + $this->metadata = $metadata; $this->handler = $handler; } @@ -69,7 +69,7 @@ public function prePersist(EventArgs $event) { $obj = $this->adapter->getObjectFromEvent($event); - if ($this->mapping->isUploadable($this->adapter->getReflectionClass($obj))) { + if ($this->metadata->isUploadable($this->adapter->getReflectionClass($obj))) { $this->handler->handleUpload($obj); } } @@ -83,7 +83,7 @@ public function preUpdate(EventArgs $event) { $obj = $this->adapter->getObjectFromEvent($event); - if ($this->mapping->isUploadable($this->adapter->getReflectionClass($obj))) { + if ($this->metadata->isUploadable($this->adapter->getReflectionClass($obj))) { $this->handler->handleUpload($obj); $this->adapter->recomputeChangeSet($event); } @@ -98,7 +98,7 @@ public function postLoad(EventArgs $event) { $obj = $this->adapter->getObjectFromEvent($event); - if ($this->mapping->isUploadable($this->adapter->getReflectionClass($obj))) { + if ($this->metadata->isUploadable($this->adapter->getReflectionClass($obj))) { $this->handler->handleHydration($obj); } } @@ -112,7 +112,7 @@ public function postRemove(EventArgs $event) { $obj = $this->adapter->getObjectFromEvent($event); - if ($this->mapping->isUploadable($this->adapter->getReflectionClass($obj))) { + if ($this->metadata->isUploadable($this->adapter->getReflectionClass($obj))) { $this->handler->handleDeletion($obj); } } diff --git a/Mapping/PropertyMappingFactory.php b/Mapping/PropertyMappingFactory.php index f26ead36..1fc3042e 100644 --- a/Mapping/PropertyMappingFactory.php +++ b/Mapping/PropertyMappingFactory.php @@ -7,7 +7,7 @@ use Vich\UploaderBundle\Adapter\AdapterInterface; use Vich\UploaderBundle\Mapping\Annotation\UploadableField; -use Vich\UploaderBundle\Mapping\MappingReader; +use Vich\UploaderBundle\Metadata\MetadataReader; use Vich\UploaderBundle\Mapping\PropertyMapping; /** @@ -23,9 +23,9 @@ class PropertyMappingFactory protected $container; /** - * @var MappingReader $mapping + * @var MetadataReader $metadata */ - protected $mapping; + protected $metadata; /** * @var AdapterInterface $adapter @@ -41,14 +41,14 @@ class PropertyMappingFactory * Constructs a new instance of PropertyMappingFactory. * * @param ContainerInterface $container The container. - * @param MappingReader $mapping The mapping mapping. + * @param MetadataReader $metadata The metadata mapping. * @param AdapterInterface $adapter The adapter. * @param array $mappings The configured mappings. */ - public function __construct(ContainerInterface $container, MappingReader $mapping, AdapterInterface $adapter, array $mappings) + public function __construct(ContainerInterface $container, MetadataReader $metadata, AdapterInterface $adapter, array $mappings) { $this->container = $container; - $this->mapping = $mapping; + $this->metadata = $metadata; $this->adapter = $adapter; $this->mappings = $mappings; } @@ -72,7 +72,7 @@ public function fromObject($obj) $this->checkUploadable($class); $mappings = array(); - foreach ($this->mapping->getUploadableFields($class) as $field => $mappingData) { + foreach ($this->metadata->getUploadableFields($class) as $field => $mappingData) { $mappings[] = $this->createMapping($obj, $field, $mappingData); } @@ -97,7 +97,7 @@ public function fromField($obj, $field) $class = $this->adapter->getReflectionClass($obj); $this->checkUploadable($class); - $mappingData = $this->mapping->getUploadableField($class, $field); + $mappingData = $this->metadata->getUploadableField($class, $field); if ($mappingData === null) { return null; } @@ -113,7 +113,7 @@ public function fromField($obj, $field) */ protected function checkUploadable(\ReflectionClass $class) { - if (!$this->mapping->isUploadable($class)) { + if (!$this->metadata->isUploadable($class)) { throw new \InvalidArgumentException('The object is not uploadable.'); } } diff --git a/Mapping/MappingReader.php b/Metadata/MetadataReader.php similarity index 79% rename from Mapping/MappingReader.php rename to Metadata/MetadataReader.php index 06561183..3039b2e4 100644 --- a/Mapping/MappingReader.php +++ b/Metadata/MetadataReader.php @@ -1,27 +1,27 @@ */ -class MappingReader +class MetadataReader { /** - * @var AgnosticReader $reader + * @var MetadataFactoryInterface $reader */ protected $reader; /** - * Constructs a new instance of the MappingReader. + * Constructs a new instance of the MetadataReader. * - * @param MetadataFactoryInterface $reader The metadata reader. + * @param MetadataFactoryInterface $reader The "low-level" metadata reader. */ public function __construct(MetadataFactoryInterface $reader) { @@ -42,6 +42,11 @@ public function isUploadable(\ReflectionClass $class) return $metadata !== null; } + /** + * Returns a list of uploadable classes. + * + * @return array A list of class names. + */ public function getUploadableClasses() { return $this->reader->getAllClassNames(); diff --git a/Resources/config/factory.xml b/Resources/config/factory.xml index 8e3c12ae..447ded1d 100644 --- a/Resources/config/factory.xml +++ b/Resources/config/factory.xml @@ -8,7 +8,7 @@ - + %vich_uploader.mappings% diff --git a/Resources/config/mapping.xml b/Resources/config/mapping.xml index cfd49a14..6a487800 100644 --- a/Resources/config/mapping.xml +++ b/Resources/config/mapping.xml @@ -43,7 +43,7 @@ - + diff --git a/Tests/EventListener/DoctrineUploaderListenerTest.php b/Tests/EventListener/DoctrineUploaderListenerTest.php index 9b37f909..535206a7 100644 --- a/Tests/EventListener/DoctrineUploaderListenerTest.php +++ b/Tests/EventListener/DoctrineUploaderListenerTest.php @@ -18,9 +18,9 @@ class DoctrineUploaderListenerTest extends \PHPUnit_Framework_TestCase protected $adapter; /** - * @var \Vich\UploaderBundle\Mapping\MappingReader $mapping + * @var \Vich\UploaderBundle\Metadata\MetadataReader $metadata */ - protected $mapping; + protected $metadata; /** * @var \Vich\UploaderBundle\Handler\UploadHandler $handler @@ -33,7 +33,7 @@ class DoctrineUploaderListenerTest extends \PHPUnit_Framework_TestCase public function setUp() { $this->adapter = $this->getAdapterMock(); - $this->mapping = $this->getMappingMock(); + $this->metadata = $this->getMetadataReaderMock(); $this->handler = $this->getHandlerMock(); } @@ -42,7 +42,7 @@ public function setUp() */ public function testGetSubscribedEvents() { - $listener = new DoctrineUploaderListener($this->adapter, $this->mapping, $this->handler); + $listener = new DoctrineUploaderListener($this->adapter, $this->metadata, $this->handler); $events = $listener->getSubscribedEvents(); $this->assertTrue(in_array('prePersist', $events)); @@ -73,7 +73,7 @@ public function testPrePersist() ->method('getReflectionClass') ->will($this->returnValue($class)); - $this->mapping + $this->metadata ->expects($this->once()) ->method('isUploadable') ->with($class) @@ -84,7 +84,7 @@ public function testPrePersist() ->method('handleUpload') ->with($obj); - $listener = new DoctrineUploaderListener($this->adapter, $this->mapping, $this->handler); + $listener = new DoctrineUploaderListener($this->adapter, $this->metadata, $this->handler); $listener->prePersist($args); } @@ -110,7 +110,7 @@ public function testPrePersistSkipsNonUploadable() ->method('getReflectionClass') ->will($this->returnValue($class)); - $this->mapping + $this->metadata ->expects($this->once()) ->method('isUploadable') ->with($class) @@ -120,7 +120,7 @@ public function testPrePersistSkipsNonUploadable() ->expects($this->never()) ->method('handleUpload'); - $listener = new DoctrineUploaderListener($this->adapter, $this->mapping, $this->handler); + $listener = new DoctrineUploaderListener($this->adapter, $this->metadata, $this->handler); $listener->prePersist($args); } @@ -151,7 +151,7 @@ public function testPreUpdate() ->method('recomputeChangeSet') ->with($args); - $this->mapping + $this->metadata ->expects($this->once()) ->method('isUploadable') ->with($class) @@ -162,7 +162,7 @@ public function testPreUpdate() ->method('handleUpload') ->with($obj); - $listener = new DoctrineUploaderListener($this->adapter, $this->mapping, $this->handler); + $listener = new DoctrineUploaderListener($this->adapter, $this->metadata, $this->handler); $listener->preUpdate($args); } @@ -188,7 +188,7 @@ public function testPreUpdateSkipsNonUploadable() ->method('getReflectionClass') ->will($this->returnValue($class)); - $this->mapping + $this->metadata ->expects($this->once()) ->method('isUploadable') ->with($class) @@ -202,7 +202,7 @@ public function testPreUpdateSkipsNonUploadable() ->expects($this->never()) ->method('handleUpload'); - $listener = new DoctrineUploaderListener($this->adapter, $this->mapping, $this->handler); + $listener = new DoctrineUploaderListener($this->adapter, $this->metadata, $this->handler); $listener->preUpdate($args); } @@ -228,7 +228,7 @@ public function testPostLoad() ->method('getReflectionClass') ->will($this->returnValue($class)); - $this->mapping + $this->metadata ->expects($this->once()) ->method('isUploadable') ->with($class) @@ -239,7 +239,7 @@ public function testPostLoad() ->method('handleHydration') ->with($obj); - $listener = new DoctrineUploaderListener($this->adapter, $this->mapping, $this->handler); + $listener = new DoctrineUploaderListener($this->adapter, $this->metadata, $this->handler); $listener->postLoad($args); } @@ -265,7 +265,7 @@ public function testPostLoadSkipsNonUploadable() ->method('getReflectionClass') ->will($this->returnValue($class)); - $this->mapping + $this->metadata ->expects($this->once()) ->method('isUploadable') ->with($class) @@ -275,7 +275,7 @@ public function testPostLoadSkipsNonUploadable() ->expects($this->never()) ->method('handleHydration'); - $listener = new DoctrineUploaderListener($this->adapter, $this->mapping, $this->handler); + $listener = new DoctrineUploaderListener($this->adapter, $this->metadata, $this->handler); $listener->postLoad($args); } @@ -301,7 +301,7 @@ public function testPostRemove() ->method('getReflectionClass') ->will($this->returnValue($class)); - $this->mapping + $this->metadata ->expects($this->once()) ->method('isUploadable') ->with($class) @@ -312,7 +312,7 @@ public function testPostRemove() ->method('handleDeletion') ->with($obj); - $listener = new DoctrineUploaderListener($this->adapter, $this->mapping, $this->handler); + $listener = new DoctrineUploaderListener($this->adapter, $this->metadata, $this->handler); $listener->postRemove($args); } @@ -338,7 +338,7 @@ public function testPostRemoveSkipsNonUploadable() ->method('getReflectionClass') ->will($this->returnValue($class)); - $this->mapping + $this->metadata ->expects($this->once()) ->method('isUploadable') ->with($class) @@ -348,7 +348,7 @@ public function testPostRemoveSkipsNonUploadable() ->expects($this->never()) ->method('handleDeletion'); - $listener = new DoctrineUploaderListener($this->adapter, $this->mapping, $this->handler); + $listener = new DoctrineUploaderListener($this->adapter, $this->metadata, $this->handler); $listener->postRemove($args); } @@ -365,13 +365,13 @@ protected function getAdapterMock() } /** - * Creates a mock mapping reader. + * Creates a mock metadata reader. * - * @return \Vich\UploaderBundle\Mapping\MappingReader The mock mapping reader. + * @return \Vich\UploaderBundle\Metadata\MetadataReader The mock metadata reader. */ - protected function getMappingMock() + protected function getMetadataReaderMock() { - return $this->getMockBuilder('Vich\UploaderBundle\Mapping\MappingReader') + return $this->getMockBuilder('Vich\UploaderBundle\Metadata\MetadataReader') ->disableOriginalConstructor() ->getMock(); } diff --git a/Tests/Mapping/PropertyMappingFactoryTest.php b/Tests/Mapping/PropertyMappingFactoryTest.php index 83eae6fe..da323984 100644 --- a/Tests/Mapping/PropertyMappingFactoryTest.php +++ b/Tests/Mapping/PropertyMappingFactoryTest.php @@ -18,9 +18,9 @@ class PropertyMappingFactoryTest extends \PHPUnit_Framework_TestCase protected $container; /** - * @var \Vich\UploaderBundle\Mapping\MappingReader $mapping + * @var \Vich\UploaderBundle\Metadata\MetadataReader $metadata */ - protected $mapping; + protected $metadata; /** * @var \Vich\UploaderBundle\Adapter\AdapterInterface $adapter @@ -33,7 +33,7 @@ class PropertyMappingFactoryTest extends \PHPUnit_Framework_TestCase public function setUp() { $this->container = $this->getContainerMock(); - $this->mapping = $this->getMappingMock(); + $this->metadata = $this->getMetadataReaderMock(); $this->adapter = $this->getAdapterMock(); } @@ -52,12 +52,12 @@ public function testFromObjectThrowsExceptionIfNotUploadable() ->method('getReflectionClass') ->will($this->returnValue(new \ReflectionClass($obj))); - $this->mapping + $this->metadata ->expects($this->once()) ->method('isUploadable') ->will($this->returnValue(false)); - $factory = new PropertyMappingFactory($this->container, $this->mapping, $this->adapter, array()); + $factory = new PropertyMappingFactory($this->container, $this->metadata, $this->adapter, array()); $factory->fromObject($obj); } @@ -86,13 +86,13 @@ public function testFromObjectOneField() ->method('getReflectionClass') ->will($this->returnValue($class)); - $this->mapping + $this->metadata ->expects($this->once()) ->method('isUploadable') ->with($class) ->will($this->returnValue(true)); - $this->mapping + $this->metadata ->expects($this->once()) ->method('getUploadableFields') ->with($class) @@ -104,7 +104,7 @@ public function testFromObjectOneField() ) ))); - $factory = new PropertyMappingFactory($this->container, $this->mapping, $this->adapter, $mappings); + $factory = new PropertyMappingFactory($this->container, $this->metadata, $this->adapter, $mappings); $mappings = $factory->fromObject($obj); $this->assertEquals(1, count($mappings)); @@ -139,13 +139,13 @@ public function testThrowsExceptionOnInvalidMappingName() ->method('getReflectionClass') ->will($this->returnValue($class)); - $this->mapping + $this->metadata ->expects($this->once()) ->method('isUploadable') ->with($class) ->will($this->returnValue(true)); - $this->mapping + $this->metadata ->expects($this->once()) ->method('getUploadableFields') ->with($class) @@ -157,8 +157,8 @@ public function testThrowsExceptionOnInvalidMappingName() ) ))); - $factory = new PropertyMappingFactory($this->container, $this->mapping, $this->adapter, $mappings); - $mappings = $factory->fromObject($obj); + $factory = new PropertyMappingFactory($this->container, $this->metadata, $this->adapter, $mappings); + $factory->fromObject($obj); } /** @@ -175,19 +175,19 @@ public function testFromFieldReturnsNullOnInvalidFieldName() ->method('getReflectionClass') ->will($this->returnValue($class)); - $this->mapping + $this->metadata ->expects($this->once()) ->method('isUploadable') ->with($class) ->will($this->returnValue(true)); - $this->mapping + $this->metadata ->expects($this->once()) ->method('getUploadableField') ->with($class) ->will($this->returnValue(null)); - $factory = new PropertyMappingFactory($this->container, $this->mapping, $this->adapter, array()); + $factory = new PropertyMappingFactory($this->container, $this->metadata, $this->adapter, array()); $mapping = $factory->fromField($obj, 'oops'); $this->assertNull($mapping); @@ -222,13 +222,13 @@ public function testConfiguredNamerRetrievedFromContainer() ->method('getReflectionClass') ->will($this->returnValue($class)); - $this->mapping + $this->metadata ->expects($this->once()) ->method('isUploadable') ->with($class) ->will($this->returnValue(true)); - $this->mapping + $this->metadata ->expects($this->once()) ->method('getUploadableFields') ->with($class) @@ -240,7 +240,7 @@ public function testConfiguredNamerRetrievedFromContainer() ) ))); - $factory = new PropertyMappingFactory($this->container, $this->mapping, $this->adapter, $mappings); + $factory = new PropertyMappingFactory($this->container, $this->metadata, $this->adapter, $mappings); $mappings = $factory->fromObject($obj); $this->assertEquals(1, count($mappings)); @@ -266,13 +266,13 @@ protected function getContainerMock() } /** - * Creates a mock mapping reader. + * Creates a mock metadata reader. * - * @return \Vich\UploaderBundle\Mapping\MappingReader The mapping reader. + * @return \Vich\UploaderBundle\Metadata\MetadataReader The metadata reader. */ - protected function getMappingMock() + protected function getMetadataReaderMock() { - return $this->getMockBuilder('Vich\UploaderBundle\Mapping\MappingReader') + return $this->getMockBuilder('Vich\UploaderBundle\Metadata\MetadataReader') ->disableOriginalConstructor() ->getMock(); } From 70c5fc41d67dd0e82ffac934b4c02b350234d5ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Wed, 11 Dec 2013 15:51:47 +0100 Subject: [PATCH 14/54] Cleaned adapters definition --- DependencyInjection/VichUploaderExtension.php | 14 ++++---------- Resources/config/adapter.xml | 4 +++- 2 files changed, 7 insertions(+), 11 deletions(-) diff --git a/DependencyInjection/VichUploaderExtension.php b/DependencyInjection/VichUploaderExtension.php index d3bda03a..f0c9820a 100644 --- a/DependencyInjection/VichUploaderExtension.php +++ b/DependencyInjection/VichUploaderExtension.php @@ -25,15 +25,6 @@ class VichUploaderExtension extends Extension 'mongodb' => 'doctrine_mongodb.odm.event_subscriber', ); - /** - * @var array $adapterMap - */ - protected $adapterMap = array( - 'orm' => 'Vich\UploaderBundle\Adapter\ORM\DoctrineORMAdapter', - 'mongodb' => 'Vich\UploaderBundle\Adapter\ODM\MongoDB\MongoDBAdapter', - 'propel' => 'Vich\UploaderBundle\Adapter\Propel\PropelAdapter' - ); - /** * Loads the extension. * @@ -59,13 +50,16 @@ public function load(array $configs, ContainerBuilder $container) $container->setParameter('vich_uploader.driver', $config['db_driver']); $container->setParameter('vich_uploader.mappings', $config['mappings']); $container->setParameter('vich_uploader.storage_service', $config['storage']); - $container->setParameter('vich_uploader.adapter.class', $this->adapterMap[$config['db_driver']]); // choose the right listener if ($config['db_driver'] !== 'propel') { $container->getDefinition('vich_uploader.listener.uploader.'.$config['db_driver'])->addTag($this->tagMap[$config['db_driver']]); } + // define the adapter listener to use + $container->setAlias('vich_uploader.adapter', 'vich_uploader.adapter.'.$config['db_driver']); + + // define the event listener to use $container->setAlias('vich_uploader.listener.uploader', 'vich_uploader.listener.uploader.'.$config['db_driver']); } diff --git a/Resources/config/adapter.xml b/Resources/config/adapter.xml index af37c005..75f4f690 100644 --- a/Resources/config/adapter.xml +++ b/Resources/config/adapter.xml @@ -6,7 +6,9 @@ - + + + From 695eaaa0b404fdcbcb7a822ae9a2baa807c3f828 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Wed, 11 Dec 2013 15:54:18 +0100 Subject: [PATCH 15/54] Fixed a few typos --- DependencyInjection/CompilerPass/RegisterPropelModelsPass.php | 4 ++-- Resources/config/listener.xml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/DependencyInjection/CompilerPass/RegisterPropelModelsPass.php b/DependencyInjection/CompilerPass/RegisterPropelModelsPass.php index 3fb0bce8..57b4eca6 100644 --- a/DependencyInjection/CompilerPass/RegisterPropelModelsPass.php +++ b/DependencyInjection/CompilerPass/RegisterPropelModelsPass.php @@ -22,8 +22,8 @@ public function process(ContainerBuilder $container) } $propelListener = $container->getDefinition('vich_uploader.listener.uploader.propel'); - $mapping = $container->get('vich_uploader.mapping_reader'); - foreach ($mapping->getUploadableClasses() as $class) { + $metadata = $container->get('vich_uploader.metadata_reader'); + foreach ($metadata->getUploadableClasses() as $class) { $propelListener->addTag('propel.event_subscriber', array( 'class' => $class )); diff --git a/Resources/config/listener.xml b/Resources/config/listener.xml index 21ed46d8..d640bfe7 100644 --- a/Resources/config/listener.xml +++ b/Resources/config/listener.xml @@ -18,7 +18,7 @@ - + From ac9c4d88e43eae2621159a29e930ae012dfe69df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Wed, 11 Dec 2013 15:54:55 +0100 Subject: [PATCH 16/54] Moar cs fixes --- EventListener/DoctrineUploaderListener.php | 6 +++--- Mapping/PropertyMappingFactory.php | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/EventListener/DoctrineUploaderListener.php b/EventListener/DoctrineUploaderListener.php index 68e0f4cc..05ba07b1 100644 --- a/EventListener/DoctrineUploaderListener.php +++ b/EventListener/DoctrineUploaderListener.php @@ -34,9 +34,9 @@ class DoctrineUploaderListener implements EventSubscriber /** * Constructs a new instance of UploaderListener. * - * @param AdapterInterface $adapter The adapter. - * @param MetadataReader $metadata The metadata reader. - * @param UploaderHandler $handler The upload handler. + * @param AdapterInterface $adapter The adapter. + * @param MetadataReader $metadata The metadata reader. + * @param UploaderHandler $handler The upload handler. */ public function __construct(AdapterInterface $adapter, MetadataReader $metadata, UploadHandler $handler) { diff --git a/Mapping/PropertyMappingFactory.php b/Mapping/PropertyMappingFactory.php index 1fc3042e..124837fd 100644 --- a/Mapping/PropertyMappingFactory.php +++ b/Mapping/PropertyMappingFactory.php @@ -41,7 +41,7 @@ class PropertyMappingFactory * Constructs a new instance of PropertyMappingFactory. * * @param ContainerInterface $container The container. - * @param MetadataReader $metadata The metadata mapping. + * @param MetadataReader $metadata The metadata mapping. * @param AdapterInterface $adapter The adapter. * @param array $mappings The configured mappings. */ From 2b847f6fdc802589c3b1f2867018a402c8505c3e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Wed, 11 Dec 2013 16:08:54 +0100 Subject: [PATCH 17/54] Added a few tests for the PropelUploader listener --- .../PropelUploaderListenerTest.php | 142 ++++++++++++++++++ 1 file changed, 142 insertions(+) create mode 100644 Tests/EventListener/PropelUploaderListenerTest.php diff --git a/Tests/EventListener/PropelUploaderListenerTest.php b/Tests/EventListener/PropelUploaderListenerTest.php new file mode 100644 index 00000000..1a872f73 --- /dev/null +++ b/Tests/EventListener/PropelUploaderListenerTest.php @@ -0,0 +1,142 @@ + + */ +class PropelUploaderListenerTest extends \PHPUnit_Framework_TestCase +{ + /** + * @var \Vich\UploaderBundle\Adapter\AdapterInterface $adapter + */ + protected $adapter; + + /** + * @var \Vich\UploaderBundle\Handler\UploadHandler $handler + */ + protected $handler; + + /** + * @var PropelUploaderListener $listener + */ + protected $listener; + + /** + * Sets up the test + */ + public function setUp() + { + $this->adapter = $this->getAdapterMock(); + $this->handler = $this->getHandlerMock(); + $this->listener = new PropelUploaderListener($this->adapter, $this->handler); + } + + /** + * Test the getSubscribedEvents method. + */ + public function testGetSubscribedEvents() + { + $events = $this->listener->getSubscribedEvents(); + + $this->assertArrayHasKey('propel.pre_insert', $events); + $this->assertArrayHasKey('propel.pre_update', $events); + $this->assertArrayHasKey('propel.post_delete', $events); + $this->assertArrayHasKey('propel.construct', $events); + } + + public function testOnUpload() + { + $obj = new DummyEntity(); + $event = $this->getEventMock(); + + $this->adapter + ->expects($this->once()) + ->method('getObjectFromEvent') + ->will($this->returnValue($obj)); + + $this->handler + ->expects($this->once()) + ->method('handleUpload') + ->with($obj); + + $this->listener->onUpload($event); + } + + public function testOnConstruct() + { + $obj = new DummyEntity(); + $event = $this->getEventMock(); + + $this->adapter + ->expects($this->once()) + ->method('getObjectFromEvent') + ->will($this->returnValue($obj)); + + $this->handler + ->expects($this->once()) + ->method('handleHydration') + ->with($obj); + + $this->listener->onConstruct($event); + } + + public function testOnDelete() + { + $obj = new DummyEntity(); + $event = $this->getEventMock(); + + $this->adapter + ->expects($this->once()) + ->method('getObjectFromEvent') + ->will($this->returnValue($obj)); + + $this->handler + ->expects($this->once()) + ->method('handleDeletion') + ->with($obj); + + $this->listener->onDelete($event); + } + + /** + * Creates a mock adapter. + * + * @return \Vich\UploaderBundle\Adapter\AdapterInterface The mock adapter. + */ + protected function getAdapterMock() + { + return $this->getMockBuilder('Vich\UploaderBundle\Adapter\AdapterInterface') + ->disableOriginalConstructor() + ->getMock(); + } + + /** + * Creates a mock handler. + * + * @return \Vich\UploaderBundle\Handler\UploadHandler The handler mock. + */ + protected function getHandlerMock() + { + return $this->getMockBuilder('Vich\UploaderBundle\Handler\UploadHandler') + ->disableOriginalConstructor() + ->getMock(); + } + + /** + * Creates a mock event. + * + * @return \Symfony\Component\EventDispatcher\GenericEvent The mock event. + */ + protected function getEventMock() + { + return $this->getMockBuilder('\Symfony\Component\EventDispatcher\GenericEvent') + ->disableOriginalConstructor() + ->getMock(); + } +} From 51ef775abfd33824d7748b7c6003eaa8a56be36a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Wed, 11 Dec 2013 18:26:38 +0000 Subject: [PATCH 18/54] Fixed doctrine related listeners --- Resources/config/listener.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Resources/config/listener.xml b/Resources/config/listener.xml index d640bfe7..2b367b08 100644 --- a/Resources/config/listener.xml +++ b/Resources/config/listener.xml @@ -16,14 +16,14 @@ - + - - + + From 8f782541f3c1e10bf74bd4a109f65bffb00c152d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Thu, 19 Dec 2013 22:55:45 +0100 Subject: [PATCH 19/54] Updated propel event dispatcher dependency dependency --- EventListener/PropelUploaderListener.php | 4 ++-- Tests/EventListener/PropelUploaderListenerTest.php | 4 ++-- composer.json | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/EventListener/PropelUploaderListener.php b/EventListener/PropelUploaderListener.php index f00cb817..7dad4a28 100644 --- a/EventListener/PropelUploaderListener.php +++ b/EventListener/PropelUploaderListener.php @@ -48,7 +48,7 @@ public static function getSubscribedEvents() 'propel.pre_insert' => 'onUpload', 'propel.pre_update' => 'onUpload', 'propel.post_delete' => 'onDelete', - 'propel.construct' => 'onConstruct', + 'propel.post_hydrate' => 'onHydrate', ); } @@ -68,7 +68,7 @@ public function onUpload(GenericEvent $event) * * @param GenericEvent $event The event. */ - public function onConstruct(GenericEvent $event) + public function onHydrate(GenericEvent $event) { $obj = $this->adapter->getObjectFromEvent($event); $this->handler->handleHydration($obj); diff --git a/Tests/EventListener/PropelUploaderListenerTest.php b/Tests/EventListener/PropelUploaderListenerTest.php index 1a872f73..f92e5f8c 100644 --- a/Tests/EventListener/PropelUploaderListenerTest.php +++ b/Tests/EventListener/PropelUploaderListenerTest.php @@ -47,7 +47,7 @@ public function testGetSubscribedEvents() $this->assertArrayHasKey('propel.pre_insert', $events); $this->assertArrayHasKey('propel.pre_update', $events); $this->assertArrayHasKey('propel.post_delete', $events); - $this->assertArrayHasKey('propel.construct', $events); + $this->assertArrayHasKey('propel.post_hydrate', $events); } public function testOnUpload() @@ -83,7 +83,7 @@ public function testOnConstruct() ->method('handleHydration') ->with($obj); - $this->listener->onConstruct($event); + $this->listener->onHydrate($event); } public function testOnDelete() diff --git a/composer.json b/composer.json index 57ea70cb..56f8b5d6 100644 --- a/composer.json +++ b/composer.json @@ -32,7 +32,7 @@ "doctrine/doctrine-bundle": "*", "doctrine/mongodb-odm-bundle": "*", "knplabs/knp-gaufrette-bundle": "*", - "willdurand/propel-eventdispatcher-bundle": "~1.0", + "willdurand/propel-eventdispatcher-bundle": ">=1.2", "symfony/yaml": "@stable" }, "autoload": { From 4ecaab6aed24a1cd76180c5c3ce2ad7b16b14458 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Sun, 22 Dec 2013 15:36:58 +0000 Subject: [PATCH 20/54] Reduced the coupling with reflection objects For now, the main benefit is that Doctrine/Propel entities are no longer required to generate file links (with Twig `vich_uploader_asset` function for instance). The following becomes possible: ```html+jinja {{ vich_uploader_asset(entry, 'imageFile', 'FooBundle\Entity\Entry') }} ``` Where `entry` isn't an object but an array. This would close the issue #138 --- EventListener/DoctrineUploaderListener.php | 13 ++-- Mapping/PropertyMappingFactory.php | 46 +++++++++--- Metadata/MetadataReader.php | 20 +++--- Storage/AbstractStorage.php | 14 ++-- Storage/FileSystemStorage.php | 4 +- Storage/StorageInterface.php | 16 +++-- Templating/Helper/UploaderHelper.php | 10 +-- .../DoctrineUploaderListenerTest.php | 16 ++--- Tests/Mapping/PropertyMappingFactoryTest.php | 72 ++++++++++++++++--- Twig/Extension/UploaderExtension.php | 10 +-- 10 files changed, 158 insertions(+), 63 deletions(-) diff --git a/EventListener/DoctrineUploaderListener.php b/EventListener/DoctrineUploaderListener.php index 05ba07b1..8f49c275 100644 --- a/EventListener/DoctrineUploaderListener.php +++ b/EventListener/DoctrineUploaderListener.php @@ -69,7 +69,7 @@ public function prePersist(EventArgs $event) { $obj = $this->adapter->getObjectFromEvent($event); - if ($this->metadata->isUploadable($this->adapter->getReflectionClass($obj))) { + if ($this->metadata->isUploadable($this->getClassName($obj))) { $this->handler->handleUpload($obj); } } @@ -83,7 +83,7 @@ public function preUpdate(EventArgs $event) { $obj = $this->adapter->getObjectFromEvent($event); - if ($this->metadata->isUploadable($this->adapter->getReflectionClass($obj))) { + if ($this->metadata->isUploadable($this->getClassName($obj))) { $this->handler->handleUpload($obj); $this->adapter->recomputeChangeSet($event); } @@ -98,7 +98,7 @@ public function postLoad(EventArgs $event) { $obj = $this->adapter->getObjectFromEvent($event); - if ($this->metadata->isUploadable($this->adapter->getReflectionClass($obj))) { + if ($this->metadata->isUploadable($this->getClassName($obj))) { $this->handler->handleHydration($obj); } } @@ -112,8 +112,13 @@ public function postRemove(EventArgs $event) { $obj = $this->adapter->getObjectFromEvent($event); - if ($this->metadata->isUploadable($this->adapter->getReflectionClass($obj))) { + if ($this->metadata->isUploadable($this->getClassName($obj))) { $this->handler->handleDeletion($obj); } } + + protected function getClassName($object) + { + return $this->adapter->getReflectionClass($object)->name; + } } diff --git a/Mapping/PropertyMappingFactory.php b/Mapping/PropertyMappingFactory.php index 124837fd..46c09bd0 100644 --- a/Mapping/PropertyMappingFactory.php +++ b/Mapping/PropertyMappingFactory.php @@ -58,17 +58,19 @@ public function __construct(ContainerInterface $container, MetadataReader $metad * configuration for the uploadable fields in the specified * object. * - * @param object $obj The object. - * @return array An array up PropertyMapping objects. + * @param object $obj The object. + * @param string $className The object's class. Mandatory if $obj can't be used to determine it. + * + * @return array An array up PropertyMapping objects. */ - public function fromObject($obj) + public function fromObject($obj, $className = null) { // @todo nothing to do here if ($obj instanceof Proxy) { $obj->__load(); } - $class = $this->adapter->getReflectionClass($obj); + $class = $this->getClassName($obj, $className); $this->checkUploadable($class); $mappings = array(); @@ -83,18 +85,20 @@ public function fromObject($obj) * Creates a property mapping object which contains the * configuration for the specified uploadable field. * - * @param object $obj The object. - * @param string $field The field. + * @param object $obj The object. + * @param string $field The field. + * @param string $className The object's class. Mandatory if $obj can't be used to determine it. + * * @return null|PropertyMapping The property mapping. */ - public function fromField($obj, $field) + public function fromField($obj, $field, $className = null) { // @todo nothing to do here if ($obj instanceof Proxy) { $obj->__load(); } - $class = $this->adapter->getReflectionClass($obj); + $class = $this->getClassName($obj, $className); $this->checkUploadable($class); $mappingData = $this->metadata->getUploadableField($class, $field); @@ -108,10 +112,11 @@ public function fromField($obj, $field) /** * Checks to see if the class is uploadable. * - * @param ReflectionClass $class The class. + * @param string $class The class name (FQCN). + * * @throws InvalidArgumentException */ - protected function checkUploadable(\ReflectionClass $class) + protected function checkUploadable($class) { if (!$this->metadata->isUploadable($class)) { throw new \InvalidArgumentException('The object is not uploadable.'); @@ -152,4 +157,25 @@ protected function createMapping($obj, $fieldName, array $mappingData) return $mapping; } + + /** + * Returns the className of the given object. + * + * @param object $object The object to inspect. + * @param string $className User specified className. + * + * @return string + */ + protected function getClassName($object, $className = null) + { + if ($className !== null) { + return $className; + } + + if (is_object($object)) { + return $this->adapter->getReflectionClass($object)->name; + } + + throw new \RuntimeException('Impossible to determine the class name. Either specify it explicitly or give an object'); + } } diff --git a/Metadata/MetadataReader.php b/Metadata/MetadataReader.php index 3039b2e4..21bfd94f 100644 --- a/Metadata/MetadataReader.php +++ b/Metadata/MetadataReader.php @@ -31,13 +31,13 @@ public function __construct(MetadataFactoryInterface $reader) /** * Tells if the given class is uploadable. * - * @param Reflectionclass $class The class to test. + * @param string $class The class name to test (FQCN). * * @return bool */ - public function isUploadable(\ReflectionClass $class) + public function isUploadable($class) { - $metadata = $this->reader->getMetadataForClass($class->name); + $metadata = $this->reader->getMetadataForClass($class); return $metadata !== null; } @@ -55,14 +55,14 @@ public function getUploadableClasses() /** * Attempts to read the uploadable fields. * - * @param \ReflectionClass $class The reflection class. + * @param string $class The class name (FQCN). * * @return array A list of uploadable fields. */ - public function getUploadableFields(\ReflectionClass $class) + public function getUploadableFields($class) { - $metadata = $this->reader->getMetadataForClass($class->getName()); - $classMetadata = $metadata->classMetadata[$class->getName()]; + $metadata = $this->reader->getMetadataForClass($class); + $classMetadata = $metadata->classMetadata[$class]; return $classMetadata->fields; } @@ -70,12 +70,12 @@ public function getUploadableFields(\ReflectionClass $class) /** * Attempts to read the mapping of a specified property. * - * @param \ReflectionClass $class The class. - * @param string $field The field + * @param string $class The class (FQCN). + * @param string $field The field * * @return null|array The field mapping. */ - public function getUploadableField(\ReflectionClass $class, $field) + public function getUploadableField($class, $field) { $fieldsMetadata = $this->getUploadableFields($class); diff --git a/Storage/AbstractStorage.php b/Storage/AbstractStorage.php index 365a1bec..34e78a15 100644 --- a/Storage/AbstractStorage.php +++ b/Storage/AbstractStorage.php @@ -120,10 +120,10 @@ abstract protected function doResolvePath($dir, $name); /** * {@inheritDoc} */ - public function resolvePath($obj, $field) + public function resolvePath($obj, $field, $className = null) { - list($mapping, $name) = $this->getFileName($obj, $field); - $dir = $mapping->getUploadDir($obj, $field); + list($mapping, $name) = $this->getFileName($obj, $field, $className); + $dir = $mapping->getUploadDir($obj, $field, $className); return $this->doResolvePath($dir, $name); } @@ -131,17 +131,17 @@ public function resolvePath($obj, $field) /** * {@inheritDoc} */ - public function resolveUri($obj, $field) + public function resolveUri($obj, $field, $className = null) { - list($mapping, $filename) = $this->getFileName($obj, $field); + list($mapping, $filename) = $this->getFileName($obj, $field, $className); $uriPrefix = $mapping->getUriPrefix(); return $filename ? ($uriPrefix . '/' . $filename) : ''; } - protected function getFileName($obj, $field) + protected function getFileName($obj, $field, $className = null) { - $mapping = $this->factory->fromField($obj, $field); + $mapping = $this->factory->fromField($obj, $field, $className); if (null === $mapping) { throw new \InvalidArgumentException(sprintf( 'Unable to find uploadable field named: "%s"', $field diff --git a/Storage/FileSystemStorage.php b/Storage/FileSystemStorage.php index dbc4fe95..08416c08 100644 --- a/Storage/FileSystemStorage.php +++ b/Storage/FileSystemStorage.php @@ -49,9 +49,9 @@ protected function doResolvePath($dir, $name) /** * {@inheritDoc} */ - public function resolveUri($obj, $field) + public function resolveUri($obj, $field, $className = null) { - list($mapping, $name) = $this->getFileName($obj, $field); + list($mapping, $name) = $this->getFileName($obj, $field, $className); $uriPrefix = $mapping->getUriPrefix(); $parts = explode($uriPrefix, $this->convertWindowsDirectorySeparator($mapping->getUploadDir($obj, $field))); diff --git a/Storage/StorageInterface.php b/Storage/StorageInterface.php index 9fa2ef65..ad4fa76d 100644 --- a/Storage/StorageInterface.php +++ b/Storage/StorageInterface.php @@ -29,19 +29,23 @@ public function remove($obj); * Resolves the path for a file based on the specified object * and field name. * - * @param object $obj The object. - * @param string $field The field. + * @param object $obj The object. + * @param string $field The field. + * @param string $className The object's class. Mandatory if $obj can't be used to determine it. + * * @return string The path. */ - public function resolvePath($obj, $field); + public function resolvePath($obj, $field, $className = null); /** * Resolves the uri for any based on the specified object * and field name. * - * @param object $obj The object. - * @param string $field The field. + * @param object $obj The object. + * @param string $field The field. + * @param string $className The object's class. Mandatory if $obj can't be used to determine it. + * * @return string The uri. */ - public function resolveUri($obj, $field); + public function resolveUri($obj, $field, $className = null); } diff --git a/Templating/Helper/UploaderHelper.php b/Templating/Helper/UploaderHelper.php index 195d3814..72487487 100644 --- a/Templating/Helper/UploaderHelper.php +++ b/Templating/Helper/UploaderHelper.php @@ -41,12 +41,14 @@ public function getName() * Gets the public path for the file associated with the * object. * - * @param object $obj The object. - * @param string $field The field. + * @param object $obj The object. + * @param string $field The field. + * @param string $className The object's class. Mandatory if $obj can't be used to determine it. + * * @return string The public asset path. */ - public function asset($obj, $field) + public function asset($obj, $field, $className = null) { - return $this->storage->resolveUri($obj, $field); + return $this->storage->resolveUri($obj, $field, $className); } } diff --git a/Tests/EventListener/DoctrineUploaderListenerTest.php b/Tests/EventListener/DoctrineUploaderListenerTest.php index 535206a7..d2b6699d 100644 --- a/Tests/EventListener/DoctrineUploaderListenerTest.php +++ b/Tests/EventListener/DoctrineUploaderListenerTest.php @@ -76,7 +76,7 @@ public function testPrePersist() $this->metadata ->expects($this->once()) ->method('isUploadable') - ->with($class) + ->with('Vich\UploaderBundle\Tests\DummyEntity') ->will($this->returnValue(true)); $this->handler @@ -113,7 +113,7 @@ public function testPrePersistSkipsNonUploadable() $this->metadata ->expects($this->once()) ->method('isUploadable') - ->with($class) + ->with('Vich\UploaderBundle\Tests\DummyEntity') ->will($this->returnValue(false)); $this->handler @@ -154,7 +154,7 @@ public function testPreUpdate() $this->metadata ->expects($this->once()) ->method('isUploadable') - ->with($class) + ->with('Vich\UploaderBundle\Tests\DummyEntity') ->will($this->returnValue(true)); $this->handler @@ -191,7 +191,7 @@ public function testPreUpdateSkipsNonUploadable() $this->metadata ->expects($this->once()) ->method('isUploadable') - ->with($class) + ->with('Vich\UploaderBundle\Tests\DummyEntity') ->will($this->returnValue(false)); $this->adapter @@ -231,7 +231,7 @@ public function testPostLoad() $this->metadata ->expects($this->once()) ->method('isUploadable') - ->with($class) + ->with('Vich\UploaderBundle\Tests\DummyEntity') ->will($this->returnValue(true)); $this->handler @@ -268,7 +268,7 @@ public function testPostLoadSkipsNonUploadable() $this->metadata ->expects($this->once()) ->method('isUploadable') - ->with($class) + ->with('Vich\UploaderBundle\Tests\DummyEntity') ->will($this->returnValue(false)); $this->handler @@ -304,7 +304,7 @@ public function testPostRemove() $this->metadata ->expects($this->once()) ->method('isUploadable') - ->with($class) + ->with('Vich\UploaderBundle\Tests\DummyEntity') ->will($this->returnValue(true)); $this->handler @@ -341,7 +341,7 @@ public function testPostRemoveSkipsNonUploadable() $this->metadata ->expects($this->once()) ->method('isUploadable') - ->with($class) + ->with('Vich\UploaderBundle\Tests\DummyEntity') ->will($this->returnValue(false)); $this->handler diff --git a/Tests/Mapping/PropertyMappingFactoryTest.php b/Tests/Mapping/PropertyMappingFactoryTest.php index da323984..2f635152 100644 --- a/Tests/Mapping/PropertyMappingFactoryTest.php +++ b/Tests/Mapping/PropertyMappingFactoryTest.php @@ -89,13 +89,13 @@ public function testFromObjectOneField() $this->metadata ->expects($this->once()) ->method('isUploadable') - ->with($class) + ->with('Vich\UploaderBundle\Tests\DummyEntity') ->will($this->returnValue(true)); $this->metadata ->expects($this->once()) ->method('getUploadableFields') - ->with($class) + ->with('Vich\UploaderBundle\Tests\DummyEntity') ->will($this->returnValue(array( 'file' => array( 'mapping' => 'dummy_file', @@ -119,6 +119,62 @@ public function testFromObjectOneField() $this->assertTrue($mapping->getInjectOnLoad()); } + /** + * Test the fromObject method with one uploadable + * field, with the object classname given. + */ + public function testFromObjectOneFieldWithClassName() + { + $obj = new DummyEntity(); + + $mappings = array( + 'dummy_file' => array( + 'upload_destination' => 'images', + 'delete_on_remove' => true, + 'delete_on_update' => true, + 'namer' => null, + 'inject_on_load' => true, + 'directory_namer' => null + ) + ); + + $this->adapter + ->expects($this->never()) + ->method('getReflectionClass'); + + $this->metadata + ->expects($this->once()) + ->method('isUploadable') + ->with('Vich\UploaderBundle\Tests\DummyEntity') + ->will($this->returnValue(true)); + + $this->metadata + ->expects($this->once()) + ->method('getUploadableFields') + ->with('Vich\UploaderBundle\Tests\DummyEntity') + ->will($this->returnValue(array( + 'file' => array( + 'mapping' => 'dummy_file', + 'propertyName' => 'file', + 'fileNameProperty' => 'fileName', + ) + ))); + + $factory = new PropertyMappingFactory($this->container, $this->metadata, $this->adapter, $mappings); + $mappings = $factory->fromObject($obj, 'Vich\UploaderBundle\Tests\DummyEntity'); + + $this->assertEquals(1, count($mappings)); + + $mapping = $mappings[0]; + + $this->assertEquals('dummy_file', $mapping->getMappingName()); + $this->assertEquals('images', $mapping->getUploadDir()); + $this->assertNull($mapping->getNamer()); + $this->assertFalse($mapping->hasNamer()); + $this->assertTrue($mapping->getDeleteOnRemove()); + $this->assertTrue($mapping->getInjectOnLoad()); + } + /** * Test that an exception is thrown when an invalid mapping name * is specified. @@ -142,13 +198,13 @@ public function testThrowsExceptionOnInvalidMappingName() $this->metadata ->expects($this->once()) ->method('isUploadable') - ->with($class) + ->with('Vich\UploaderBundle\Tests\DummyEntity') ->will($this->returnValue(true)); $this->metadata ->expects($this->once()) ->method('getUploadableFields') - ->with($class) + ->with('Vich\UploaderBundle\Tests\DummyEntity') ->will($this->returnValue(array( 'file' => array( 'mapping' => 'dummy_file', @@ -178,13 +234,13 @@ public function testFromFieldReturnsNullOnInvalidFieldName() $this->metadata ->expects($this->once()) ->method('isUploadable') - ->with($class) + ->with('Vich\UploaderBundle\Tests\DummyEntity') ->will($this->returnValue(true)); $this->metadata ->expects($this->once()) ->method('getUploadableField') - ->with($class) + ->with('Vich\UploaderBundle\Tests\DummyEntity') ->will($this->returnValue(null)); $factory = new PropertyMappingFactory($this->container, $this->metadata, $this->adapter, array()); @@ -225,13 +281,13 @@ public function testConfiguredNamerRetrievedFromContainer() $this->metadata ->expects($this->once()) ->method('isUploadable') - ->with($class) + ->with('Vich\UploaderBundle\Tests\DummyEntity') ->will($this->returnValue(true)); $this->metadata ->expects($this->once()) ->method('getUploadableFields') - ->with($class) + ->with('Vich\UploaderBundle\Tests\DummyEntity') ->will($this->returnValue(array( 'file' => array( 'mapping' => 'dummy_file', diff --git a/Twig/Extension/UploaderExtension.php b/Twig/Extension/UploaderExtension.php index f711406f..4414667a 100644 --- a/Twig/Extension/UploaderExtension.php +++ b/Twig/Extension/UploaderExtension.php @@ -59,12 +59,14 @@ public function getFunctions() * Gets the public path for the file associated with the uploadable * object. * - * @param object $obj The object. - * @param string $field The field. + * @param object $obj The object. + * @param string $field The field. + * @param string $className The object's class. Mandatory if $obj can't be used to determine it. + * * @return string The public path. */ - public function asset($obj, $field) + public function asset($obj, $field, $className = null) { - return $this->helper->asset($obj, $field); + return $this->helper->asset($obj, $field, $className); } } From 2382acf3c8f5347a8e4a2e7762963a15bb4df3f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Sun, 22 Dec 2013 15:55:14 +0000 Subject: [PATCH 21/54] File namers should use PropertyMapping instances instead of relying on reflection (BC break inside) --- Naming/NamerInterface.php | 9 ++++++--- Naming/OrignameNamer.php | 14 ++++---------- Naming/UniqidNamer.php | 10 +++------- Storage/AbstractStorage.php | 2 +- Tests/Naming/OrignameNamerTest.php | 12 +++++++++++- Tests/Naming/UniqidNamerTest.php | 12 +++++++++++- Tests/Storage/FileSystemStorageTest.php | 8 ++++---- 7 files changed, 40 insertions(+), 27 deletions(-) diff --git a/Naming/NamerInterface.php b/Naming/NamerInterface.php index fff4b833..b00a8909 100644 --- a/Naming/NamerInterface.php +++ b/Naming/NamerInterface.php @@ -2,6 +2,8 @@ namespace Vich\UploaderBundle\Naming; +use Vich\UploaderBundle\Mapping\PropertyMapping; + /** * NamerInterface. * @@ -12,9 +14,10 @@ interface NamerInterface /** * Creates a name for the file being uploaded. * - * @param object $obj The object the upload is attached to. - * @param string $field The name of the uploadable field to generate a name for. + * @param Propertymapping $mapping The mapping to use to manipulate the given object. + * @param object $object The object the upload is attached to. + * * @return string The file name. */ - public function name($obj, $field); + public function name(PropertyMapping $mapping, $object); } diff --git a/Naming/OrignameNamer.php b/Naming/OrignameNamer.php index 5955d8de..8958594e 100644 --- a/Naming/OrignameNamer.php +++ b/Naming/OrignameNamer.php @@ -2,8 +2,7 @@ namespace Vich\UploaderBundle\Naming; -use Symfony\Component\HttpFoundation\File\File; -use Symfony\Component\HttpFoundation\File\UploadedFile; +use Vich\UploaderBundle\Mapping\PropertyMapping; /** * OrignameNamer @@ -15,16 +14,11 @@ class OrignameNamer implements NamerInterface /** * {@inheritDoc} */ - public function name($obj, $field) + public function name(PropertyMapping $mapping, $object) { - $refObj = new \ReflectionObject($obj); + $file = $mapping->getFile($object); - $refProp = $refObj->getProperty($field); - $refProp->setAccessible(true); - - $file = $refProp->getValue($obj); - - /** @var $file UploadedFile */ + /** @var $file \Symfony\Component\HttpFoundation\File\UploadedFile */ return uniqid().'_'.$file->getClientOriginalName(); } diff --git a/Naming/UniqidNamer.php b/Naming/UniqidNamer.php index 3f3b86df..234e81f1 100644 --- a/Naming/UniqidNamer.php +++ b/Naming/UniqidNamer.php @@ -3,6 +3,7 @@ namespace Vich\UploaderBundle\Naming; use Symfony\Component\HttpFoundation\File\UploadedFile; +use Vich\UploaderBundle\Mapping\PropertyMapping; /** * UniqidNamer @@ -14,14 +15,9 @@ class UniqidNamer implements NamerInterface /** * {@inheritDoc} */ - public function name($obj, $field) + public function name(PropertyMapping $mapping, $object) { - $refObj = new \ReflectionObject($obj); - - $refProp = $refObj->getProperty($field); - $refProp->setAccessible(true); - - $file = $refProp->getValue($obj); + $file = $mapping->getFile($object); $name = uniqid(); if ($extension = $this->getExtension($file)) { diff --git a/Storage/AbstractStorage.php b/Storage/AbstractStorage.php index 34e78a15..dc9ad57b 100644 --- a/Storage/AbstractStorage.php +++ b/Storage/AbstractStorage.php @@ -59,7 +59,7 @@ public function upload($obj) } if ($mapping->hasNamer()) { - $name = $mapping->getNamer()->name($obj, $mapping->getFilePropertyName()); + $name = $mapping->getNamer()->name($mapping, $obj); } else { $name = $file->getClientOriginalName(); } diff --git a/Tests/Naming/OrignameNamerTest.php b/Tests/Naming/OrignameNamerTest.php index e2b2da01..466f57c1 100644 --- a/Tests/Naming/OrignameNamerTest.php +++ b/Tests/Naming/OrignameNamerTest.php @@ -38,8 +38,18 @@ public function testNameReturnsAnUniqueName($name, $pattern) $entity = new DummyEntity; $entity->setFile($file); + $mapping = $this->getMockBuilder('Vich\UploaderBundle\Mapping\PropertyMapping') + ->disableOriginalConstructor() + ->getMock(); + + $mapping + ->expects($this->once()) + ->method('getFile') + ->with($entity) + ->will($this->returnValue($file)); + $namer = new OrignameNamer(); - $this->assertRegExp($pattern, $namer->name($entity, 'file')); + $this->assertRegExp($pattern, $namer->name($mapping, $entity)); } } diff --git a/Tests/Naming/UniqidNamerTest.php b/Tests/Naming/UniqidNamerTest.php index 63d7e07f..f34d6aec 100644 --- a/Tests/Naming/UniqidNamerTest.php +++ b/Tests/Naming/UniqidNamerTest.php @@ -45,8 +45,18 @@ public function testNameReturnsAnUniqueName($originalName, $guessedExtension, $p $entity = new DummyEntity; $entity->setFile($file); + $mapping = $this->getMockBuilder('Vich\UploaderBundle\Mapping\PropertyMapping') + ->disableOriginalConstructor() + ->getMock(); + + $mapping + ->expects($this->once()) + ->method('getFile') + ->with($entity) + ->will($this->returnValue($file)); + $namer = new UniqidNamer(); - $this->assertRegExp($pattern, $namer->name($entity, 'file')); + $this->assertRegExp($pattern, $namer->name($mapping, $entity)); } } diff --git a/Tests/Storage/FileSystemStorageTest.php b/Tests/Storage/FileSystemStorageTest.php index 2aadcd93..18a2b279 100644 --- a/Tests/Storage/FileSystemStorageTest.php +++ b/Tests/Storage/FileSystemStorageTest.php @@ -380,17 +380,17 @@ public function testFilenameWithDirectoriesIsUploadedToCorrectDirectory($dir, $f ->disableOriginalConstructor() ->getMock(); + $mapping = $this->getMappingMock(); + $namer = $this->getMockBuilder('Vich\UploaderBundle\Naming\NamerInterface') ->disableOriginalConstructor() ->getMock(); $namer ->expects($this->once()) ->method('name') - ->with($obj, $name) + ->with($mapping, $obj) ->will($this->returnValue($filename)); - $mapping = $this->getMappingMock(); - $mapping ->expects($this->once()) ->method('getNamer') @@ -420,7 +420,7 @@ public function testFilenameWithDirectoriesIsUploadedToCorrectDirectory($dir, $f $mapping ->expects($this->once()) ->method('getUploadDir') - ->with($obj,$name) + ->with($obj, $name) ->will($this->returnValue($dir)); $this->factory From d2edc2d16bb4223f28349fbc28127448711508d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Sun, 22 Dec 2013 16:16:20 +0000 Subject: [PATCH 22/54] Cleaned last usages of Reflection in adapters as they now are useless --- Adapter/AdapterInterface.php | 10 ++--- Adapter/ODM/MongoDB/MongoDBAdapter.php | 9 ++--- Adapter/ORM/DoctrineORMAdapter.php | 9 ++--- Adapter/Propel/PropelAdapter.php | 5 +-- EventListener/DoctrineUploaderListener.php | 13 ++---- Mapping/PropertyMappingFactory.php | 2 +- .../ODM/MongoDB/MongoDBAdapterTest.php | 12 +++--- Tests/Adapter/ORM/DoctrineORMAdapterTest.php | 12 +++--- Tests/Adapter/Propel/PropelAdapterTest.php | 12 ++---- .../DoctrineUploaderListenerTest.php | 40 ++++++++----------- Tests/Mapping/PropertyMappingFactoryTest.php | 38 ++++++++---------- 11 files changed, 67 insertions(+), 95 deletions(-) diff --git a/Adapter/AdapterInterface.php b/Adapter/AdapterInterface.php index b55d485d..6b459b15 100644 --- a/Adapter/AdapterInterface.php +++ b/Adapter/AdapterInterface.php @@ -25,11 +25,11 @@ public function getObjectFromEvent($event); public function recomputeChangeSet($event); /** - * Gets the reflection class for the object, taking - * proxies into account. + * Gets class name for the object, taking proxies into account. * - * @param object $object The object. - * @return \ReflectionClass The reflection class. + * @param object $object The object. + * + * @return string The FQCN of the className. */ - public function getReflectionClass($object); + public function getClassName($object); } diff --git a/Adapter/ODM/MongoDB/MongoDBAdapter.php b/Adapter/ODM/MongoDB/MongoDBAdapter.php index 071d9ff4..431a3263 100644 --- a/Adapter/ODM/MongoDB/MongoDBAdapter.php +++ b/Adapter/ODM/MongoDB/MongoDBAdapter.php @@ -18,7 +18,6 @@ class MongoDBAdapter implements AdapterInterface public function getObjectFromEvent($event) { /* @var $event \Doctrine\Common\EventArgs */ - return $event->getDocument(); } @@ -39,12 +38,12 @@ public function recomputeChangeSet($event) /** * {@inheritDoc} */ - public function getReflectionClass($object) + public function getClassName($object) { if ($object instanceof Proxy) { - return new \ReflectionClass(get_parent_class($object)); + return get_parent_class($object); + } else { + return get_class($object); } - - return new \ReflectionClass($object); } } diff --git a/Adapter/ORM/DoctrineORMAdapter.php b/Adapter/ORM/DoctrineORMAdapter.php index 3bbf3d65..9a2a0ebf 100644 --- a/Adapter/ORM/DoctrineORMAdapter.php +++ b/Adapter/ORM/DoctrineORMAdapter.php @@ -18,7 +18,6 @@ class DoctrineORMAdapter implements AdapterInterface public function getObjectFromEvent($event) { /* @var $event \Doctrine\Common\EventArgs */ - return $event->getEntity(); } @@ -39,12 +38,12 @@ public function recomputeChangeSet($event) /** * {@inheritDoc} */ - public function getReflectionClass($object) + public function getClassName($object) { if ($object instanceof Proxy) { - return new \ReflectionClass(get_parent_class($object)); + return get_parent_class($object); + } else { + return get_class($object); } - - return new \ReflectionClass($object); } } diff --git a/Adapter/Propel/PropelAdapter.php b/Adapter/Propel/PropelAdapter.php index ec505b43..1d3b97d6 100644 --- a/Adapter/Propel/PropelAdapter.php +++ b/Adapter/Propel/PropelAdapter.php @@ -17,7 +17,6 @@ class PropelAdapter implements AdapterInterface public function getObjectFromEvent($event) { /* @var $event \Symfony\Component\EventDispatcher\GenericEvent */ - return $event->getSubject(); } @@ -31,8 +30,8 @@ public function recomputeChangeSet($event) /** * {@inheritDoc} */ - public function getReflectionClass($object) + public function getClassName($object) { - return new \ReflectionClass($object); + return get_class($object); } } diff --git a/EventListener/DoctrineUploaderListener.php b/EventListener/DoctrineUploaderListener.php index 8f49c275..698028f4 100644 --- a/EventListener/DoctrineUploaderListener.php +++ b/EventListener/DoctrineUploaderListener.php @@ -69,7 +69,7 @@ public function prePersist(EventArgs $event) { $obj = $this->adapter->getObjectFromEvent($event); - if ($this->metadata->isUploadable($this->getClassName($obj))) { + if ($this->metadata->isUploadable($this->adapter->getClassName($obj))) { $this->handler->handleUpload($obj); } } @@ -83,7 +83,7 @@ public function preUpdate(EventArgs $event) { $obj = $this->adapter->getObjectFromEvent($event); - if ($this->metadata->isUploadable($this->getClassName($obj))) { + if ($this->metadata->isUploadable($this->adapter->getClassName($obj))) { $this->handler->handleUpload($obj); $this->adapter->recomputeChangeSet($event); } @@ -98,7 +98,7 @@ public function postLoad(EventArgs $event) { $obj = $this->adapter->getObjectFromEvent($event); - if ($this->metadata->isUploadable($this->getClassName($obj))) { + if ($this->metadata->isUploadable($this->adapter->getClassName($obj))) { $this->handler->handleHydration($obj); } } @@ -112,13 +112,8 @@ public function postRemove(EventArgs $event) { $obj = $this->adapter->getObjectFromEvent($event); - if ($this->metadata->isUploadable($this->getClassName($obj))) { + if ($this->metadata->isUploadable($this->adapter->getClassName($obj))) { $this->handler->handleDeletion($obj); } } - - protected function getClassName($object) - { - return $this->adapter->getReflectionClass($object)->name; - } } diff --git a/Mapping/PropertyMappingFactory.php b/Mapping/PropertyMappingFactory.php index 46c09bd0..9690804d 100644 --- a/Mapping/PropertyMappingFactory.php +++ b/Mapping/PropertyMappingFactory.php @@ -173,7 +173,7 @@ protected function getClassName($object, $className = null) } if (is_object($object)) { - return $this->adapter->getReflectionClass($object)->name; + return $this->adapter->getClassName($object); } throw new \RuntimeException('Impossible to determine the class name. Either specify it explicitly or give an object'); diff --git a/Tests/Adapter/ODM/MongoDB/MongoDBAdapterTest.php b/Tests/Adapter/ODM/MongoDB/MongoDBAdapterTest.php index f5f774e8..8ca3d7f8 100644 --- a/Tests/Adapter/ODM/MongoDB/MongoDBAdapterTest.php +++ b/Tests/Adapter/ODM/MongoDB/MongoDBAdapterTest.php @@ -40,32 +40,32 @@ public function testGetObjectFromEvent() /** * Tests the getReflectionClass method. */ - public function testGetReflectionClass() + public function testGetClassName() { if (!interface_exists('Doctrine\ODM\MongoDB\Proxy\Proxy')) { $this->markTestSkipped('Doctrine\ODM\MongoDB\Proxy\Proxy does not exist.'); } else { $obj = new DummyEntity(); $adapter = new MongoDBAdapter(); - $class = $adapter->getReflectionClass($obj); + $class = $adapter->getClassName($obj); - $this->assertEquals($class->getName(), get_class($obj)); + $this->assertEquals('Vich\UploaderBundle\Tests\DummyEntity', $class); } } /** * Tests the getReflectionClass method with a proxy. */ - public function testGetReflectionClassProxy() + public function testGetClassNameWithProxy() { if (!interface_exists('Doctrine\ODM\MongoDB\Proxy\Proxy')) { $this->markTestSkipped('Doctrine\ODM\MongoDB\Proxy\Proxy does not exist.'); } else { $obj = new DummyEntityProxyMongo(); $adapter = new MongoDBAdapter(); - $class = $adapter->getReflectionClass($obj); + $class = $adapter->getClassName($obj); - $this->assertEquals($class->getName(), get_parent_class($obj)); + $this->assertEquals('Vich\UploaderBundle\Tests\DummyEntity', $class); } } } diff --git a/Tests/Adapter/ORM/DoctrineORMAdapterTest.php b/Tests/Adapter/ORM/DoctrineORMAdapterTest.php index 7110d97c..a3d807d8 100644 --- a/Tests/Adapter/ORM/DoctrineORMAdapterTest.php +++ b/Tests/Adapter/ORM/DoctrineORMAdapterTest.php @@ -40,32 +40,32 @@ public function testGetObjectFromEvent() /** * Tests the getReflectionClass method. */ - public function testGetReflectionClass() + public function testGetClassName() { if (!interface_exists('Doctrine\ORM\Proxy\Proxy')) { $this->markTestSkipped('Doctrine\ORM\Proxy\Proxy does not exist.'); } else { $obj = new DummyEntity(); $adapter = new DoctrineORMAdapter(); - $class = $adapter->getReflectionClass($obj); + $class = $adapter->getClassName($obj); - $this->assertEquals($class->getName(), get_class($obj)); + $this->assertEquals('Vich\UploaderBundle\Tests\DummyEntity', $class); } } /** * Tests the getReflectionClass method with a proxy. */ - public function testGetReflectionClassProxy() + public function testGetClassNameWithProxy() { if (!interface_exists('Doctrine\ORM\Proxy\Proxy')) { $this->markTestSkipped('Doctrine\ORM\Proxy\Proxy does not exist.'); } else { $obj = new DummyEntityProxyORM(); $adapter = new DoctrineORMAdapter(); - $class = $adapter->getReflectionClass($obj); + $class = $adapter->getClassName($obj); - $this->assertEquals($class->getName(), get_parent_class($obj)); + $this->assertEquals('Vich\UploaderBundle\Tests\DummyEntity', $class); } } } diff --git a/Tests/Adapter/Propel/PropelAdapterTest.php b/Tests/Adapter/Propel/PropelAdapterTest.php index 87305da5..5987e71f 100644 --- a/Tests/Adapter/Propel/PropelAdapterTest.php +++ b/Tests/Adapter/Propel/PropelAdapterTest.php @@ -11,9 +11,6 @@ */ class PropelAdapterTest extends \PHPUnit_Framework_TestCase { - /** - * Test the getObjectFromEvent method. - */ public function testGetObjectFromEvent() { $event = $this->getMock('\Symfony\Component\EventDispatcher\GenericEvent'); @@ -26,16 +23,13 @@ public function testGetObjectFromEvent() $this->assertSame(42, $adapter->getObjectFromEvent($event)); } - /** - * Tests the getReflectionClass method. - */ - public function testGetReflectionClass() + public function testGetClassName() { $adapter = new PropelAdapter(); $obj = new \DateTime(); - $class = $adapter->getReflectionClass($obj); + $class = $adapter->getClassName($obj); - $this->assertSame('DateTime', $class->getName()); + $this->assertSame('DateTime', $class); } } diff --git a/Tests/EventListener/DoctrineUploaderListenerTest.php b/Tests/EventListener/DoctrineUploaderListenerTest.php index d2b6699d..91946ae7 100644 --- a/Tests/EventListener/DoctrineUploaderListenerTest.php +++ b/Tests/EventListener/DoctrineUploaderListenerTest.php @@ -57,7 +57,6 @@ public function testGetSubscribedEvents() public function testPrePersist() { $obj = new DummyEntity(); - $class = new \ReflectionClass($obj); $args = $this->getMockBuilder('Doctrine\Common\EventArgs') ->disableOriginalConstructor() @@ -70,8 +69,8 @@ public function testPrePersist() $this->adapter ->expects($this->once()) - ->method('getReflectionClass') - ->will($this->returnValue($class)); + ->method('getClassName') + ->will($this->returnValue('Vich\UploaderBundle\Tests\DummyEntity')); $this->metadata ->expects($this->once()) @@ -94,7 +93,6 @@ public function testPrePersist() public function testPrePersistSkipsNonUploadable() { $obj = new DummyEntity(); - $class = new \ReflectionClass($obj); $args = $this->getMockBuilder('Doctrine\Common\EventArgs') ->disableOriginalConstructor() @@ -107,8 +105,8 @@ public function testPrePersistSkipsNonUploadable() $this->adapter ->expects($this->once()) - ->method('getReflectionClass') - ->will($this->returnValue($class)); + ->method('getClassName') + ->will($this->returnValue('Vich\UploaderBundle\Tests\DummyEntity')); $this->metadata ->expects($this->once()) @@ -130,7 +128,6 @@ public function testPrePersistSkipsNonUploadable() public function testPreUpdate() { $obj = new DummyEntity(); - $class = new \ReflectionClass($obj); $args = $this->getMockBuilder('Doctrine\Common\EventArgs') ->disableOriginalConstructor() @@ -143,8 +140,8 @@ public function testPreUpdate() $this->adapter ->expects($this->once()) - ->method('getReflectionClass') - ->will($this->returnValue($class)); + ->method('getClassName') + ->will($this->returnValue('Vich\UploaderBundle\Tests\DummyEntity')); $this->adapter ->expects($this->once()) @@ -172,7 +169,6 @@ public function testPreUpdate() public function testPreUpdateSkipsNonUploadable() { $obj = new DummyEntity(); - $class = new \ReflectionClass($obj); $args = $this->getMockBuilder('Doctrine\Common\EventArgs') ->disableOriginalConstructor() @@ -185,8 +181,8 @@ public function testPreUpdateSkipsNonUploadable() $this->adapter ->expects($this->once()) - ->method('getReflectionClass') - ->will($this->returnValue($class)); + ->method('getClassName') + ->will($this->returnValue('Vich\UploaderBundle\Tests\DummyEntity')); $this->metadata ->expects($this->once()) @@ -212,7 +208,6 @@ public function testPreUpdateSkipsNonUploadable() public function testPostLoad() { $obj = new DummyEntity(); - $class = new \ReflectionClass($obj); $args = $this->getMockBuilder('Doctrine\Common\EventArgs') ->disableOriginalConstructor() @@ -225,8 +220,8 @@ public function testPostLoad() $this->adapter ->expects($this->once()) - ->method('getReflectionClass') - ->will($this->returnValue($class)); + ->method('getClassName') + ->will($this->returnValue('Vich\UploaderBundle\Tests\DummyEntity')); $this->metadata ->expects($this->once()) @@ -249,7 +244,6 @@ public function testPostLoad() public function testPostLoadSkipsNonUploadable() { $obj = new DummyEntity(); - $class = new \ReflectionClass($obj); $args = $this->getMockBuilder('Doctrine\Common\EventArgs') ->disableOriginalConstructor() @@ -262,8 +256,8 @@ public function testPostLoadSkipsNonUploadable() $this->adapter ->expects($this->once()) - ->method('getReflectionClass') - ->will($this->returnValue($class)); + ->method('getClassName') + ->will($this->returnValue('Vich\UploaderBundle\Tests\DummyEntity')); $this->metadata ->expects($this->once()) @@ -285,7 +279,6 @@ public function testPostLoadSkipsNonUploadable() public function testPostRemove() { $obj = new DummyEntity(); - $class = new \ReflectionClass($obj); $args = $this->getMockBuilder('Doctrine\Common\EventArgs') ->disableOriginalConstructor() @@ -298,8 +291,8 @@ public function testPostRemove() $this->adapter ->expects($this->once()) - ->method('getReflectionClass') - ->will($this->returnValue($class)); + ->method('getClassName') + ->will($this->returnValue('Vich\UploaderBundle\Tests\DummyEntity')); $this->metadata ->expects($this->once()) @@ -322,7 +315,6 @@ public function testPostRemove() public function testPostRemoveSkipsNonUploadable() { $obj = new DummyEntity(); - $class = new \ReflectionClass($obj); $args = $this->getMockBuilder('Doctrine\Common\EventArgs') ->disableOriginalConstructor() @@ -335,8 +327,8 @@ public function testPostRemoveSkipsNonUploadable() $this->adapter ->expects($this->once()) - ->method('getReflectionClass') - ->will($this->returnValue($class)); + ->method('getClassName') + ->will($this->returnValue('Vich\UploaderBundle\Tests\DummyEntity')); $this->metadata ->expects($this->once()) diff --git a/Tests/Mapping/PropertyMappingFactoryTest.php b/Tests/Mapping/PropertyMappingFactoryTest.php index 2f635152..fcacd8e4 100644 --- a/Tests/Mapping/PropertyMappingFactoryTest.php +++ b/Tests/Mapping/PropertyMappingFactoryTest.php @@ -45,12 +45,10 @@ public function setUp() */ public function testFromObjectThrowsExceptionIfNotUploadable() { - $obj = new \StdClass(); - $this->adapter ->expects($this->once()) - ->method('getReflectionClass') - ->will($this->returnValue(new \ReflectionClass($obj))); + ->method('getClassName') + ->will($this->returnValue('StdClass')); $this->metadata ->expects($this->once()) @@ -58,7 +56,7 @@ public function testFromObjectThrowsExceptionIfNotUploadable() ->will($this->returnValue(false)); $factory = new PropertyMappingFactory($this->container, $this->metadata, $this->adapter, array()); - $factory->fromObject($obj); + $factory->fromObject(new \StdClass()); } /** @@ -68,7 +66,6 @@ public function testFromObjectThrowsExceptionIfNotUploadable() public function testFromObjectOneField() { $obj = new DummyEntity(); - $class = new \ReflectionClass($obj); $mappings = array( 'dummy_file' => array( @@ -82,9 +79,9 @@ public function testFromObjectOneField() ); $this->adapter - ->expects($this->any()) - ->method('getReflectionClass') - ->will($this->returnValue($class)); + ->expects($this->once()) + ->method('getClassName') + ->will($this->returnValue('Vich\UploaderBundle\Tests\DummyEntity')); $this->metadata ->expects($this->once()) @@ -140,7 +137,7 @@ public function testFromObjectOneFieldWithClassName() $this->adapter ->expects($this->never()) - ->method('getReflectionClass'); + ->method('getClassName'); $this->metadata ->expects($this->once()) @@ -184,16 +181,15 @@ public function testFromObjectOneFieldWithClassName() public function testThrowsExceptionOnInvalidMappingName() { $obj = new DummyEntity(); - $class = new \ReflectionClass($obj); $mappings = array( 'bad_name' => array() ); $this->adapter - ->expects($this->any()) - ->method('getReflectionClass') - ->will($this->returnValue($class)); + ->expects($this->once()) + ->method('getClassName') + ->will($this->returnValue('Vich\UploaderBundle\Tests\DummyEntity')); $this->metadata ->expects($this->once()) @@ -224,12 +220,11 @@ public function testThrowsExceptionOnInvalidMappingName() public function testFromFieldReturnsNullOnInvalidFieldName() { $obj = new DummyEntity(); - $class = new \ReflectionClass($obj); $this->adapter - ->expects($this->any()) - ->method('getReflectionClass') - ->will($this->returnValue($class)); + ->expects($this->once()) + ->method('getClassName') + ->will($this->returnValue('Vich\UploaderBundle\Tests\DummyEntity')); $this->metadata ->expects($this->once()) @@ -252,7 +247,6 @@ public function testFromFieldReturnsNullOnInvalidFieldName() public function testConfiguredNamerRetrievedFromContainer() { $obj = new DummyEntity(); - $class = new \ReflectionClass($obj); $mappings = array( 'dummy_file' => array( @@ -274,9 +268,9 @@ public function testConfiguredNamerRetrievedFromContainer() ->will($this->returnValue($namer)); $this->adapter - ->expects($this->any()) - ->method('getReflectionClass') - ->will($this->returnValue($class)); + ->expects($this->once()) + ->method('getClassName') + ->will($this->returnValue('Vich\UploaderBundle\Tests\DummyEntity')); $this->metadata ->expects($this->once()) From 0867935acca368f9526b0c3057ce853edb338d42 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Sun, 22 Dec 2013 19:44:23 +0000 Subject: [PATCH 23/54] Allow older versions of the PropertyAccess component --- Mapping/PropertyMapping.php | 2 +- composer.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Mapping/PropertyMapping.php b/Mapping/PropertyMapping.php index 39b95e2d..80d12c6c 100644 --- a/Mapping/PropertyMapping.php +++ b/Mapping/PropertyMapping.php @@ -61,7 +61,7 @@ protected function getAccessor() return $this->accessor; } - return $this->accessor = PropertyAccess::createPropertyAccessor(); + return $this->accessor = PropertyAccess::getPropertyAccessor(); } /** diff --git a/composer.json b/composer.json index 56f8b5d6..f50bb141 100644 --- a/composer.json +++ b/composer.json @@ -15,7 +15,7 @@ "php": ">=5.3.2", "symfony/framework-bundle": "~2.0", "jms/metadata": "~1.5", - "symfony/property-access": ">=2.3", + "symfony/property-access": ">=2.2,<3.0", "symfony/finder": ">=2.0" }, "require-dev": { From dee3819bde2209df1bb125aedf6c8c9e04708a70 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Sun, 22 Dec 2013 21:34:37 +0000 Subject: [PATCH 24/54] Fixed namespace for Naming testcases --- Tests/Naming/OrignameNamerTest.php | 5 ++--- Tests/Naming/UniqidNamerTest.php | 2 +- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/Tests/Naming/OrignameNamerTest.php b/Tests/Naming/OrignameNamerTest.php index 466f57c1..ba0abc02 100644 --- a/Tests/Naming/OrignameNamerTest.php +++ b/Tests/Naming/OrignameNamerTest.php @@ -1,10 +1,9 @@ Date: Sun, 22 Dec 2013 21:34:45 +0000 Subject: [PATCH 25/54] Fixed phpunit config file --- phpunit.xml.dist | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/phpunit.xml.dist b/phpunit.xml.dist index f53c420f..00b2cfdf 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -1,6 +1,16 @@ - + @@ -14,8 +24,9 @@ ./Resources ./Tests + ./vendor - + From 8df892069e7f305a479b086a12bec52ab3128f42 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Sun, 22 Dec 2013 22:26:14 +0000 Subject: [PATCH 26/54] Started to work on the testsuite (less code, more meaningfull tests and total fs isolation) --- Storage/StorageInterface.php | 20 +- Tests/Storage/FileSystemStorageTest.php | 549 +++++++++++------------- composer.json | 1 + 3 files changed, 262 insertions(+), 308 deletions(-) diff --git a/Storage/StorageInterface.php b/Storage/StorageInterface.php index ad4fa76d..96770f35 100644 --- a/Storage/StorageInterface.php +++ b/Storage/StorageInterface.php @@ -10,40 +10,40 @@ interface StorageInterface { /** - * Uploads the files in the uploadable fields of the - * specified object according to the property configuration. + * Uploads the files in the uploadable fields of the specified object + * according to the property configuration. * * @param object $obj The object. */ public function upload($obj); /** - * Removes the files associated with the object if configured to - * do so. + * Removes the files associated with the object if configured to do so. * * @param object $obj The object. */ public function remove($obj); /** - * Resolves the path for a file based on the specified object - * and field name. + * Resolves the path for a file based on the specified object and field + * name. * * @param object $obj The object. * @param string $field The field. - * @param string $className The object's class. Mandatory if $obj can't be used to determine it. + * @param string $className The object's class. Mandatory if $obj can't be + * used to determine it. * * @return string The path. */ public function resolvePath($obj, $field, $className = null); /** - * Resolves the uri for any based on the specified object - * and field name. + * Resolves the uri for any based on the specified object and field name. * * @param object $obj The object. * @param string $field The field. - * @param string $className The object's class. Mandatory if $obj can't be used to determine it. + * @param string $className The object's class. Mandatory if $obj can't be + * used to determine it. * * @return string The uri. */ diff --git a/Tests/Storage/FileSystemStorageTest.php b/Tests/Storage/FileSystemStorageTest.php index 18a2b279..16e5bec3 100644 --- a/Tests/Storage/FileSystemStorageTest.php +++ b/Tests/Storage/FileSystemStorageTest.php @@ -2,6 +2,9 @@ namespace Vich\UploaderBundle\Tests\Storage; +use org\bovigo\vfs\vfsStream; +use org\bovigo\vfs\vfsStreamWrapper; + use Vich\UploaderBundle\Storage\FileSystemStorage; use Vich\UploaderBundle\Tests\DummyEntity; @@ -17,425 +20,217 @@ class FileSystemStorageTest extends \PHPUnit_Framework_TestCase */ protected $factory; + /** + * @var PropertyMapping + */ + protected $mapping; + + /** + * @var DummyEntity + */ + protected $object; + + /** + * @var FileSystemStorage + */ + protected $storage; + + /** + * @var vfsStreamDirectory + */ + protected $fsRoot; + /** * Sets up the test. */ public function setUp() { $this->factory = $this->getFactoryMock(); + $this->mapping = $this->getMappingMock(); + $this->object = new DummyEntity(); + $this->storage = new FileSystemStorage($this->factory); + + $this->root = vfsStream::setup('vich_uploader_bundle', null, array( + 'uploads' => array( + 'test.txt' => 'some content' + ), + )); + + $this->factory + ->expects($this->any()) + ->method('fromObject') + ->with($this->object) + ->will($this->returnValue(array($this->mapping))); } /** * Tests the upload method skips a mapping which has a null * uploadable property value. + * + * @group upload */ public function testUploadSkipsMappingOnNullFile() { - $obj = new DummyEntity(); - - $mapping = $this->getMappingMock(); - $mapping - ->expects($this->once()) - ->method('getFile') - ->will($this->returnValue(null)); - - $mapping - ->expects($this->never()) - ->method('hasNamer'); - - $mapping - ->expects($this->never()) - ->method('getNamer'); - $mapping - ->expects($this->never()) - ->method('getFileName'); - - $this->factory - ->expects($this->once()) - ->method('fromObject') - ->with($obj) - ->will($this->returnValue(array($mapping))); - - $storage = new FileSystemStorage($this->factory); - $storage->upload($obj); + $this->mapping + ->expects($this->once()) + ->method('getFile') + ->will($this->returnValue(null)); + $this->mapping + ->expects($this->never()) + ->method('hasNamer'); + $this->mapping + ->expects($this->never()) + ->method('getNamer'); + $this->mapping + ->expects($this->never()) + ->method('getFileName'); + + $this->storage->upload($this->object); } /** * Tests the upload method skips a mapping which has an uploadable * field property value that is not an instance of UploadedFile. + * + * @group upload */ public function testUploadSkipsMappingOnNonUploadedFileInstance() { - $obj = new DummyEntity(); - - $mapping = $this->getMappingMock(); - $file = $this->getMockBuilder('Symfony\Component\HttpFoundation\File\File') ->disableOriginalConstructor() ->getMock(); - $mapping + $this->mapping ->expects($this->once()) ->method('getFile') ->will($this->returnValue($file)); - $mapping + $this->mapping ->expects($this->never()) ->method('hasNamer'); - $mapping + $this->mapping ->expects($this->never()) ->method('getNamer'); - $mapping + $this->mapping ->expects($this->never()) ->method('getFileName'); - $this->factory - ->expects($this->once()) - ->method('fromObject') - ->with($obj) - ->will($this->returnValue(array($mapping))); - - $storage = new FileSystemStorage($this->factory); - $storage->upload($obj); - } - - /** - * Test the remove method does not remove a file that is configured - * to not be deleted upon removal of the entity. - */ - public function testRemoveSkipsConfiguredNotToDeleteOnRemove() - { - $obj = new DummyEntity(); - - $mapping = $this->getMappingMock(); - $mapping - ->expects($this->once()) - ->method('getDeleteOnRemove') - ->will($this->returnValue(false)); - - $mapping - ->expects($this->never()) - ->method('getFileName'); - - $this->factory - ->expects($this->once()) - ->method('fromObject') - ->with($obj) - ->will($this->returnValue(array($mapping))); - - $storage = new FileSystemStorage($this->factory); - $storage->remove($obj); - } - - /** - * Test the remove method skips trying to remove a file whose file name - * property value returns null. - */ - public function testRemoveSkipsNullFileNameProperty() - { - $obj = new DummyEntity(); - - $mapping = $this->getMappingMock(); - $mapping - ->expects($this->once()) - ->method('getDeleteOnRemove') - ->will($this->returnValue(true)); - - $mapping - ->expects($this->once()) - ->method('getFileName') - ->will($this->returnValue(null)); - - $mapping - ->expects($this->never()) - ->method('getUploadDir'); - - $this->factory - ->expects($this->once()) - ->method('fromObject') - ->with($obj) - ->will($this->returnValue(array($mapping))); - - $storage = new FileSystemStorage($this->factory); - $storage->remove($obj); - } - - /** - * Test the remove method skips trying to remove a file that no longer exists - */ - public function testRemoveSkipsNonExistingFile() - { - $obj = new DummyEntity(); - - $mapping = $this->getMappingMock(); - $mapping - ->expects($this->once()) - ->method('getDeleteOnRemove') - ->will($this->returnValue(true)); - - $mapping - ->expects($this->once()) - ->method('getUploadDir') - ->will($this->returnValue('/tmp')); - - $mapping - ->expects($this->once()) - ->method('getFileName') - ->will($this->returnValue('file.txt')); - - $this->factory - ->expects($this->once()) - ->method('fromObject') - ->with($obj) - ->will($this->returnValue(array($mapping))); - - $storage = new FileSystemStorage($this->factory); - try { - $storage->remove($obj); - } catch (\Exception $e) { - $this->fail('We tried to remove nonexistent file'); - } - } - - /** - * Test the resolve path method. - */ - public function testResolvePath() - { - $obj = new DummyEntity(); - - $mapping = $this->getMappingMock(); - $mapping - ->expects($this->once()) - ->method('getUploadDir') - ->will($this->returnValue('/tmp')); - $mapping - ->expects($this->once()) - ->method('getFileName') - ->will($this->returnValue('file.txt')); - - $this->factory - ->expects($this->once()) - ->method('fromField') - ->with($obj, 'file') - ->will($this->returnValue($mapping)); - - $storage = new FileSystemStorage($this->factory); - $path = $storage->resolvePath($obj, 'file'); - - $this->assertEquals(sprintf('/tmp%sfile.txt', DIRECTORY_SEPARATOR), $path); - } - - /** - * Test the resolve uri - * - * @dataProvider resolveUriDataProvider - */ - public function testResolveUri($uploadDir, $uri) - { - $obj = new DummyEntity(); - - $mapping = $this->getMappingMock(); - $mapping - ->expects($this->once()) - ->method('getUploadDir') - ->will($this->returnValue($uploadDir)); - - $mapping - ->expects($this->once()) - ->method('getUriPrefix') - ->will($this->returnValue('/uploads')); - - $mapping - ->expects($this->once()) - ->method('getFileName') - ->will($this->returnValue('file.txt')); - - $this->factory - ->expects($this->once()) - ->method('fromField') - ->with($obj, 'file') - ->will($this->returnValue($mapping)); - - $storage = new FileSystemStorage($this->factory); - $path = $storage->resolveUri($obj, 'file'); - - $this->assertEquals($uri, $path); - } - - public function resolveUriDataProvider() - { - return array( - array( - '/abs/path/web/uploads', - '/uploads/file.txt' - ), - array( - 'c:\abs\path\web\uploads', - '/uploads/file.txt' - ), - array( - '/abs/path/web/project/web/uploads', - '/uploads/file.txt' - ), - array( - '/abs/path/web/project/web/uploads/custom/dir', - '/uploads/custom/dir/file.txt' - ), - ); - } - - /** - * Test the resolve path method throws exception - * when an invaid field name is specified. - * - * @expectedException \InvalidArgumentException - */ - public function testResolvePathThrowsExceptionOnInvalidFieldName() - { - $obj = new DummyEntity(); - - $this->factory - ->expects($this->once()) - ->method('fromField') - ->with($obj, 'oops') - ->will($this->returnValue(null)); - - $storage = new FileSystemStorage($this->factory); - $storage->resolvePath($obj, 'oops'); + $this->storage->upload($this->object); } /** - * Test that file upload moves uploaded file to correct directory and with correct filename + * Test that file upload moves uploaded file to correct directory and with correct filename + * @group upload */ public function testUploadedFileIsCorrectlyMoved() { - $obj = new DummyEntity(); - $file = $this->getMockBuilder('Symfony\Component\HttpFoundation\File\UploadedFile') ->disableOriginalConstructor() ->getMock(); $file - ->expects($this->any()) + ->expects($this->once()) ->method('getClientOriginalName') ->will($this->returnValue('filename.txt')); - $mapping = $this->getMappingMock(); - - $mapping + $this->mapping ->expects($this->once()) ->method('getFile') - ->with($obj) + ->with($this->object) ->will($this->returnValue($file)); - $mapping - ->expects($this->any()) + $this->mapping + ->expects($this->once()) ->method('getFilePropertyName') ->will($this->returnValue('file')); - $mapping + $this->mapping ->expects($this->once()) ->method('getDeleteOnUpdate') ->will($this->returnValue(false)); - $mapping + $this->mapping ->expects($this->once()) ->method('hasNamer') ->will($this->returnValue(false)); - $mapping + $this->mapping ->expects($this->once()) ->method('getUploadDir') - ->with($obj, 'file') + ->with($this->object, 'file') ->will($this->returnValue('/dir')); - $this->factory - ->expects($this->once()) - ->method('fromObject') - ->with($obj) - ->will($this->returnValue(array($mapping))); - $file ->expects($this->once()) ->method('move') ->with('/dir', 'filename.txt'); - $storage = new FileSystemStorage($this->factory); - $storage->upload($obj); + $this->storage->upload($this->object); } /** - * Test file upload when filename contains directories + * Test file upload when filename contains directories + * * @dataProvider filenameWithDirectoriesDataProvider + * @group upload */ public function testFilenameWithDirectoriesIsUploadedToCorrectDirectory($dir, $filename, $expectedDir, $expectedFileName) { - $obj = new DummyEntity(); $name = 'lala'; $file = $this->getMockBuilder('Symfony\Component\HttpFoundation\File\UploadedFile') ->disableOriginalConstructor() ->getMock(); - $mapping = $this->getMappingMock(); - $namer = $this->getMockBuilder('Vich\UploaderBundle\Naming\NamerInterface') ->disableOriginalConstructor() ->getMock(); $namer ->expects($this->once()) ->method('name') - ->with($mapping, $obj) + ->with($this->mapping, $this->object) ->will($this->returnValue($filename)); - $mapping + $this->mapping ->expects($this->once()) ->method('getNamer') ->will($this->returnValue($namer)); - $mapping - ->expects($this->any()) + $this->mapping + ->expects($this->once()) ->method('getFilePropertyName') ->will($this->returnValue($name)); - $mapping + $this->mapping ->expects($this->once()) ->method('getFile') - ->with($obj) + ->with($this->object) ->will($this->returnValue($file)); - $mapping + $this->mapping ->expects($this->once()) ->method('getDeleteOnUpdate') ->will($this->returnValue(false)); - $mapping + $this->mapping ->expects($this->once()) ->method('hasNamer') ->will($this->returnValue(true)); - $mapping + $this->mapping ->expects($this->once()) ->method('getUploadDir') - ->with($obj, $name) + ->with($this->object, $name) ->will($this->returnValue($dir)); - $this->factory - ->expects($this->once()) - ->method('fromObject') - ->with($obj) - ->will($this->returnValue(array($mapping))); - $file ->expects($this->once()) ->method('move') ->with($expectedDir, $expectedFileName); - $storage = new FileSystemStorage($this->factory); - $storage->upload($obj); + $this->storage->upload($this->object); } @@ -458,21 +253,179 @@ public function filenameWithDirectoriesDataProvider() } /** - * Creates a mock factory. + * @dataProvider removeDataProvider + */ + public function testRemove($deleteOnRemove, $uploadDir, $fileName) + { + $this->mapping + ->expects($this->once()) + ->method('getDeleteOnRemove') + ->will($this->returnValue($deleteOnRemove)); + + // if the file should be deleted, we'll need its name + if ($deleteOnRemove) { + $this->mapping + ->expects($this->once()) + ->method('getFileName') + ->will($this->returnValue($fileName)); + } else { + $this->mapping + ->expects($this->never()) + ->method('getFileName'); + } + + // if the file should be deleted and we have its name, then we need the + // upload dir + if ($deleteOnRemove && $fileName !== null) { + $this->mapping + ->expects($this->once()) + ->method('getUploadDir') + ->will($this->returnValue($this->root->url() . DIRECTORY_SEPARATOR . $uploadDir)); + } else { + $this->mapping + ->expects($this->never()) + ->method('getUploadDir'); + } + + $this->storage->remove($this->object); + + // the file should have been deleted + if ($deleteOnRemove && $fileName !== null) { + $this->assertFalse($this->root->hasChild($uploadDir . DIRECTORY_SEPARATOR . $fileName)); + } + } + + public function removeDataProvider() + { + return array( + // deleteOnRemove uploadDir fileName + // don't configured to be deleted upon removal of the entity + array(false, null, null), + // configured, but not file present + array(true, null, null), + // configured and present in the filesystem + array(true, '/uploads', 'test.txt'), + // configured, but file already deleted + array(true, '/uploads', 'file.txt'), + ); + } + + /** + * Test the resolve path method. + * + * @group resolvePath + */ + public function testResolvePath() + { + $this->mapping = $this->getMappingMock(); + $this->mapping + ->expects($this->once()) + ->method('getUploadDir') + ->will($this->returnValue('/tmp')); + $this->mapping + ->expects($this->once()) + ->method('getFileName') + ->will($this->returnValue('file.txt')); + + $this->factory + ->expects($this->once()) + ->method('fromField') + ->with($this->object, 'file') + ->will($this->returnValue($this->mapping)); + + $path = $this->storage->resolvePath($this->object, 'file'); + + $this->assertEquals(sprintf('/tmp%sfile.txt', DIRECTORY_SEPARATOR), $path); + } + + /** + * Test the resolve path method throws exception + * when an invaid field name is specified. + * + * @expectedException \InvalidArgumentException + * @group resolvePath + */ + public function testResolvePathThrowsExceptionOnInvalidFieldName() + { + $this->factory + ->expects($this->once()) + ->method('fromField') + ->with($this->object, 'oops') + ->will($this->returnValue(null)); + + $this->storage->resolvePath($this->object, 'oops'); + } + + /** + * Test the resolve uri + * + * @dataProvider resolveUriDataProvider + * @group resolveUri + */ + public function testResolveUri($uploadDir, $uri) + { + $this->mapping + ->expects($this->once()) + ->method('getUploadDir') + ->will($this->returnValue($uploadDir)); + + $this->mapping + ->expects($this->once()) + ->method('getUriPrefix') + ->will($this->returnValue('/uploads')); + + $this->mapping + ->expects($this->once()) + ->method('getFileName') + ->will($this->returnValue('file.txt')); + + $this->factory + ->expects($this->once()) + ->method('fromField') + ->with($this->object, 'file') + ->will($this->returnValue($this->mapping)); + + $this->assertEquals($uri, $this->storage->resolveUri($this->object, 'file')); + } + + public function resolveUriDataProvider() + { + return array( + array( + '/abs/path/web/uploads', + '/uploads/file.txt' + ), + array( + 'c:\abs\path\web\uploads', + '/uploads/file.txt' + ), + array( + '/abs/path/web/project/web/uploads', + '/uploads/file.txt' + ), + array( + '/abs/path/web/project/web/uploads/custom/dir', + '/uploads/custom/dir/file.txt' + ), + ); + } + + /** + * Creates a mock mapping-factory. * * @return \Vich\UploaderBundle\Mapping\PropertyMappingFactory The factory. */ protected function getFactoryMock() { return $this->getMockBuilder('Vich\UploaderBundle\Mapping\PropertyMappingFactory') - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); } protected function getMappingMock() { return $this->getMockBuilder('Vich\UploaderBundle\Mapping\PropertyMapping') - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); } } diff --git a/composer.json b/composer.json index f50bb141..00c43a3f 100644 --- a/composer.json +++ b/composer.json @@ -19,6 +19,7 @@ "symfony/finder": ">=2.0" }, "require-dev": { + "mikey179/vfsStream": "~1.0", "doctrine/orm": "@stable", "doctrine/mongodb-odm": "@dev", "knplabs/knp-gaufrette-bundle": "*", From 1a263393534c989fa648a0a3be92a3119a662a14 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Tue, 24 Dec 2013 10:51:29 +0000 Subject: [PATCH 27/54] Fixed tests due to rebase --- Tests/Storage/GaufretteStorageTest.php | 15 +++------------ 1 file changed, 3 insertions(+), 12 deletions(-) diff --git a/Tests/Storage/GaufretteStorageTest.php b/Tests/Storage/GaufretteStorageTest.php index 3dc0e09b..5f20723f 100644 --- a/Tests/Storage/GaufretteStorageTest.php +++ b/Tests/Storage/GaufretteStorageTest.php @@ -199,16 +199,7 @@ public function testResolvePathWithChangedProtocol() { $obj = new DummyEntity(); - $mapping = $this->getMock('Vich\UploaderBundle\Mapping\PropertyMapping'); - - $prop = $this->getMockBuilder('\ReflectionProperty') - ->disableOriginalConstructor() - ->getMock(); - $prop - ->expects($this->once()) - ->method('getValue') - ->with($obj) - ->will($this->returnValue('file.txt')); + $mapping = $this->getMappingMock(); $mapping ->expects($this->once()) @@ -217,8 +208,8 @@ public function testResolvePathWithChangedProtocol() $mapping ->expects($this->once()) - ->method('getFileNameProperty') - ->will($this->returnValue($prop)); + ->method('getFileName') + ->will($this->returnValue('file.txt')); $this->factory ->expects($this->once()) From 8538aca539b3a5d7697324663301ab0975c87872 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Tue, 24 Dec 2013 11:03:09 +0000 Subject: [PATCH 28/54] Cleaned a bit more the FileSystemStorage test --- Tests/Storage/FileSystemStorageTest.php | 68 +++++++++---------------- 1 file changed, 23 insertions(+), 45 deletions(-) diff --git a/Tests/Storage/FileSystemStorageTest.php b/Tests/Storage/FileSystemStorageTest.php index 16e5bec3..db749db8 100644 --- a/Tests/Storage/FileSystemStorageTest.php +++ b/Tests/Storage/FileSystemStorageTest.php @@ -64,12 +64,10 @@ public function setUp() } /** - * Tests the upload method skips a mapping which has a null - * uploadable property value. - * - * @group upload + * @dataProvider invalidFileProvider + * @group upload */ - public function testUploadSkipsMappingOnNullFile() + public function testUploadSkipsMappingOnInvalidFile() { $this->mapping ->expects($this->once()) @@ -88,40 +86,26 @@ public function testUploadSkipsMappingOnNullFile() $this->storage->upload($this->object); } - /** - * Tests the upload method skips a mapping which has an uploadable - * field property value that is not an instance of UploadedFile. - * - * @group upload - */ - public function testUploadSkipsMappingOnNonUploadedFileInstance() + public function invalidFileProvider() { $file = $this->getMockBuilder('Symfony\Component\HttpFoundation\File\File') - ->disableOriginalConstructor() - ->getMock(); - - $this->mapping - ->expects($this->once()) - ->method('getFile') - ->will($this->returnValue($file)); - - $this->mapping - ->expects($this->never()) - ->method('hasNamer'); - - $this->mapping - ->expects($this->never()) - ->method('getNamer'); - - $this->mapping - ->expects($this->never()) - ->method('getFileName'); + ->disableOriginalConstructor() + ->getMock(); - $this->storage->upload($this->object); + return array( + // skipped because null + array( null ), + // skipped because not even a file + array( new \DateTime() ), + // skipped because not instance of UploadedFile + array( $file ), + ); } /** - * Test that file upload moves uploaded file to correct directory and with correct filename + * Test that file upload moves uploaded file to correct directory and with + * correct filename. + * * @group upload */ public function testUploadedFileIsCorrectlyMoved() @@ -150,11 +134,6 @@ public function testUploadedFileIsCorrectlyMoved() ->method('getDeleteOnUpdate') ->will($this->returnValue(false)); - $this->mapping - ->expects($this->once()) - ->method('hasNamer') - ->will($this->returnValue(false)); - $this->mapping ->expects($this->once()) ->method('getUploadDir') @@ -173,8 +152,8 @@ public function testUploadedFileIsCorrectlyMoved() /** * Test file upload when filename contains directories * - * @dataProvider filenameWithDirectoriesDataProvider - * @group upload + * @dataProvider filenameWithDirectoriesDataProvider + * @group upload */ public function testFilenameWithDirectoriesIsUploadedToCorrectDirectory($dir, $filename, $expectedDir, $expectedFileName) { @@ -317,7 +296,6 @@ public function removeDataProvider() */ public function testResolvePath() { - $this->mapping = $this->getMappingMock(); $this->mapping ->expects($this->once()) ->method('getUploadDir') @@ -342,8 +320,8 @@ public function testResolvePath() * Test the resolve path method throws exception * when an invaid field name is specified. * - * @expectedException \InvalidArgumentException - * @group resolvePath + * @expectedException InvalidArgumentException + * @group resolvePath */ public function testResolvePathThrowsExceptionOnInvalidFieldName() { @@ -359,8 +337,8 @@ public function testResolvePathThrowsExceptionOnInvalidFieldName() /** * Test the resolve uri * - * @dataProvider resolveUriDataProvider - * @group resolveUri + * @dataProvider resolveUriDataProvider + * @group resolveUri */ public function testResolveUri($uploadDir, $uri) { From c3cf0a83ddbacce0b7e6d154530d0d72b0b08ba3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Tue, 24 Dec 2013 11:58:44 +0000 Subject: [PATCH 29/54] Fixed the FileInjector tests so that the filesystem isn't impacted anymore --- Tests/Injector/FileInjectorTest.php | 171 +++++++++++------------- Tests/Storage/FileSystemStorageTest.php | 3 +- 2 files changed, 82 insertions(+), 92 deletions(-) diff --git a/Tests/Injector/FileInjectorTest.php b/Tests/Injector/FileInjectorTest.php index dc928661..46d2bdd5 100644 --- a/Tests/Injector/FileInjectorTest.php +++ b/Tests/Injector/FileInjectorTest.php @@ -2,29 +2,39 @@ namespace Vich\UploaderBundle\Tests\Injector; -use Vich\UploaderBundle\Injector\FileInjector; +use org\bovigo\vfs\vfsStream; use Symfony\Component\HttpFoundation\File\File; + +use Vich\UploaderBundle\Injector\FileInjector; use Vich\UploaderBundle\Tests\DummyEntity; /** * FileInjectorTest. * - * @todo use vfsStream (http://phpunit.de/manual/current/en/test-doubles.html#test-doubles.mocking-the-filesystem) - * * @author Dustin Dobervich */ class FileInjectorTest extends \PHPUnit_Framework_TestCase { /** - * @var Vich\UploaderBundle\Mapping\PropertyMappingFactory $factory + * @var \Vich\UploaderBundle\Mapping\PropertyMappingFactory $factory */ protected $factory; /** - * @var Vich\UploaderBundle\Storage\GaufretteStorage $storage + * @var \Vich\UploaderBundle\Storage\StorageInterface $storage */ protected $storage; + /** + * @var FileInjector + */ + protected $injector; + + /** + * @var vfsStreamDirectory + */ + protected $root; + /** * Sets up the test. */ @@ -32,6 +42,14 @@ public function setUp() { $this->factory = $this->getMockMappingFactory(); $this->storage = $this->getMockStorage(); + $this->root = vfsStream::setup('vich_uploader_bundle', null, array( + 'uploads' => array( + 'file.txt' => 'some content', + 'image.png' => 'some content', + ), + )); + + $this->injector = new FileInjector($this->factory, $this->storage); } /** @@ -39,30 +57,23 @@ public function setUp() */ public function testInjectsOneFile() { - $uploadDir = __DIR__ . '/..'; - $name = 'file.txt'; $filePropertyName = 'file'; - - file_put_contents(sprintf('%s/%s', $uploadDir, $name), ''); - $obj = $this->getMock('Vich\UploaderBundle\Tests\DummyEntity'); - $fileMapping = $this->getMockBuilder('Vich\UploaderBundle\Mapping\PropertyMapping') - ->disableOriginalConstructor() - ->getMock(); + $fileMapping = $this->getPropertyMappingMock(); $fileMapping ->expects($this->once()) ->method('getInjectOnLoad') ->will($this->returnValue(true)); $fileMapping - ->expects($this->exactly(1)) + ->expects($this->once()) ->method('getFilePropertyName') ->will($this->returnValue($filePropertyName)); $fileMapping - ->expects($this->exactly(1)) + ->expects($this->once()) ->method('setFile') ->with($this->equalTo($obj), $this->callback(function ($file) { - return $file instanceof \Symfony\Component\HttpFoundation\File\File; + return $file instanceof File; })); $this->factory @@ -75,12 +86,9 @@ public function testInjectsOneFile() ->expects($this->once()) ->method('resolvePath') ->with($this->equalTo($obj), $this->equalTo($filePropertyName)) - ->will($this->returnValue($uploadDir)); - - $inject = new FileInjector($this->factory, $this->storage); - $inject->injectFiles($obj); + ->will($this->returnValue($this->getUploadDir() . DIRECTORY_SEPARATOR . 'file.txt')); - unlink(sprintf('%s/%s', $uploadDir, $name)); + $this->injector->injectFiles($obj); } /** @@ -88,49 +96,30 @@ public function testInjectsOneFile() */ public function testInjectTwoFiles() { - $uploadDir = __DIR__ . '/..'; - $fileName = 'file.txt'; - $imageName = 'image.txt'; - - file_put_contents(sprintf('%s/%s', $uploadDir, $fileName), ''); - file_put_contents(sprintf('%s/%s', $uploadDir, $imageName), ''); - $obj = $this->getMock('Vich\UploaderBundle\Tests\TwoFieldsDummyEntity'); - $fileMapping = $this->getMockBuilder('Vich\UploaderBundle\Mapping\PropertyMapping') - ->disableOriginalConstructor() - ->getMock(); + $fileMapping = $this->getPropertyMappingMock(); $fileMapping ->expects($this->once()) - ->method('getInjectOnLoad') - ->will($this->returnValue(true)); - $fileMapping - ->expects($this->exactly(1)) ->method('getFilePropertyName') ->will($this->returnValue('file')); $fileMapping - ->expects($this->exactly(1)) + ->expects($this->once()) ->method('setFile') ->with($this->equalTo($obj), $this->callback(function ($file) { - return $file instanceof \Symfony\Component\HttpFoundation\File\File; + return $file instanceof File; })); - $imageMapping = $this->getMockBuilder('Vich\UploaderBundle\Mapping\PropertyMapping') - ->disableOriginalConstructor() - ->getMock(); + $imageMapping = $this->getPropertyMappingMock(); $imageMapping ->expects($this->once()) - ->method('getInjectOnLoad') - ->will($this->returnValue(true)); - $imageMapping - ->expects($this->exactly(1)) ->method('getFilePropertyName') ->will($this->returnValue('image')); $imageMapping - ->expects($this->exactly(1)) + ->expects($this->once()) ->method('setFile') ->with($this->equalTo($obj), $this->callback(function ($file) { - return $file instanceof \Symfony\Component\HttpFoundation\File\File; + return $file instanceof File; })); $this->factory @@ -142,13 +131,12 @@ public function testInjectTwoFiles() $this->storage ->expects($this->exactly(2)) ->method('resolvePath') - ->will($this->returnValue($uploadDir)); - - $inject = new FileInjector($this->factory, $this->storage); - $inject->injectFiles($obj); + ->will($this->onConsecutiveCalls( + $this->getUploadDir() . DIRECTORY_SEPARATOR . 'file.txt', + $this->getUploadDir() . DIRECTORY_SEPARATOR . 'image.png' + )); - unlink(sprintf('%s/%s', $uploadDir, $fileName)); - unlink(sprintf('%s/%s', $uploadDir, $imageName)); + $this->injector->injectFiles($obj); } /** @@ -159,14 +147,10 @@ public function testInjectionIsSkippedIfNotConfigured() { $obj = $this->getMock('Vich\UploaderBundle\Tests\DummyEntity'); - $fileMapping = $this->getMockBuilder('Vich\UploaderBundle\Mapping\PropertyMapping') - ->disableOriginalConstructor() - ->getMock(); - + $fileMapping = $this->getPropertyMappingMock(false); $fileMapping - ->expects($this->once()) - ->method('getInjectOnLoad') - ->will($this->returnValue(false)); + ->expects($this->never()) + ->method('setFile'); $this->factory ->expects($this->once()) @@ -174,34 +158,21 @@ public function testInjectionIsSkippedIfNotConfigured() ->with($obj) ->will($this->returnValue(array($fileMapping))); - $inject = new FileInjector($this->factory, $this->storage); - $inject->injectFiles($obj); - - $this->assertEquals(null, $obj->getFile()); + $this->injector->injectFiles($obj); } - /** - * Test that if the file name property returns a null value - * then no file is injected. - */ public function testPropertyIsNullWhenFileNamePropertyIsNull() { - $uploadDir = __DIR__ . '/..'; - $obj = $this->getMock('Vich\UploaderBundle\Tests\DummyEntity'); - $fileMapping = $this->getMockBuilder('Vich\UploaderBundle\Mapping\PropertyMapping') - ->disableOriginalConstructor() - ->getMock(); - + $fileMapping = $this->getPropertyMappingMock(); $fileMapping ->expects($this->once()) - ->method('getInjectOnLoad') - ->will($this->returnValue(true)); - $fileMapping - ->expects($this->exactly(1)) ->method('getFilePropertyName') ->will($this->returnValue('file')); + $fileMapping + ->expects($this->never()) + ->method('setFile'); $this->factory ->expects($this->once()) @@ -212,36 +183,56 @@ public function testPropertyIsNullWhenFileNamePropertyIsNull() $this->storage ->expects($this->once()) ->method('resolvePath') - ->will($this->returnValue($uploadDir)); - - $inject = new FileInjector($this->factory, $this->storage); - $inject->injectFiles($obj); + ->will($this->throwException(new \InvalidArgumentException)); - $this->assertEquals(null, $obj->getFile()); + $this->injector->injectFiles($obj); } /** * Gets a mock mapping factory. * - * @return Vich\UploaderBundle\Mapping\PropertyMappingFactory The factory. + * @return \Vich\UploaderBundle\Mapping\PropertyMappingFactory The factory. */ protected function getMockMappingFactory() { return $this->getMockBuilder('Vich\UploaderBundle\Mapping\PropertyMappingFactory') - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); + } + + /** + * Gets a mocked property mapping. + * + * @return \Vich\UploaderBundle\Mapping\PropertyMapping The property. + */ + protected function getPropertyMappingMock($inject_on_load_enabled = true) + { + $mapping = $this->getMockBuilder('Vich\UploaderBundle\Mapping\PropertyMapping') + ->disableOriginalConstructor() + ->getMock(); + + $mapping + ->expects($this->once()) + ->method('getInjectOnLoad') + ->will($this->returnValue($inject_on_load_enabled)); + + return $mapping; } /** * Gets a mock storage. * - * @return Vich\UploaderBundle\Storage\GaufretteStorage Storage + * @return \Vich\UploaderBundle\Storage\StorageInterface */ protected function getMockStorage() { - return $this->getMockBuilder('Vich\UploaderBundle\Storage\GaufretteStorage') - ->disableOriginalConstructor() - ->getMock() - ; + return $this->getMockBuilder('Vich\UploaderBundle\Storage\StorageInterface') + ->disableOriginalConstructor() + ->getMock(); + } + + protected function getUploadDir() + { + return $this->root->url() . DIRECTORY_SEPARATOR . 'uploads'; } } diff --git a/Tests/Storage/FileSystemStorageTest.php b/Tests/Storage/FileSystemStorageTest.php index db749db8..274580f9 100644 --- a/Tests/Storage/FileSystemStorageTest.php +++ b/Tests/Storage/FileSystemStorageTest.php @@ -3,7 +3,6 @@ namespace Vich\UploaderBundle\Tests\Storage; use org\bovigo\vfs\vfsStream; -use org\bovigo\vfs\vfsStreamWrapper; use Vich\UploaderBundle\Storage\FileSystemStorage; use Vich\UploaderBundle\Tests\DummyEntity; @@ -38,7 +37,7 @@ class FileSystemStorageTest extends \PHPUnit_Framework_TestCase /** * @var vfsStreamDirectory */ - protected $fsRoot; + protected $root; /** * Sets up the test. From b939d47d6d0db1d75240b40c502944e9b758cfbd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Tue, 24 Dec 2013 12:08:40 +0000 Subject: [PATCH 30/54] Fixed a few checkstyles --- Adapter/ODM/MongoDB/MongoDBAdapter.php | 1 + Adapter/ORM/DoctrineORMAdapter.php | 1 + Adapter/Propel/PropelAdapter.php | 1 + Tests/Injector/FileInjectorTest.php | 4 ++-- Tests/Metadata/Driver/YamlTest.php | 8 ++++---- 5 files changed, 9 insertions(+), 6 deletions(-) diff --git a/Adapter/ODM/MongoDB/MongoDBAdapter.php b/Adapter/ODM/MongoDB/MongoDBAdapter.php index 431a3263..3c4c34b3 100644 --- a/Adapter/ODM/MongoDB/MongoDBAdapter.php +++ b/Adapter/ODM/MongoDB/MongoDBAdapter.php @@ -18,6 +18,7 @@ class MongoDBAdapter implements AdapterInterface public function getObjectFromEvent($event) { /* @var $event \Doctrine\Common\EventArgs */ + return $event->getDocument(); } diff --git a/Adapter/ORM/DoctrineORMAdapter.php b/Adapter/ORM/DoctrineORMAdapter.php index 9a2a0ebf..38d70c00 100644 --- a/Adapter/ORM/DoctrineORMAdapter.php +++ b/Adapter/ORM/DoctrineORMAdapter.php @@ -18,6 +18,7 @@ class DoctrineORMAdapter implements AdapterInterface public function getObjectFromEvent($event) { /* @var $event \Doctrine\Common\EventArgs */ + return $event->getEntity(); } diff --git a/Adapter/Propel/PropelAdapter.php b/Adapter/Propel/PropelAdapter.php index 1d3b97d6..1faf80c3 100644 --- a/Adapter/Propel/PropelAdapter.php +++ b/Adapter/Propel/PropelAdapter.php @@ -17,6 +17,7 @@ class PropelAdapter implements AdapterInterface public function getObjectFromEvent($event) { /* @var $event \Symfony\Component\EventDispatcher\GenericEvent */ + return $event->getSubject(); } diff --git a/Tests/Injector/FileInjectorTest.php b/Tests/Injector/FileInjectorTest.php index 46d2bdd5..87e8c1dc 100644 --- a/Tests/Injector/FileInjectorTest.php +++ b/Tests/Injector/FileInjectorTest.php @@ -205,7 +205,7 @@ protected function getMockMappingFactory() * * @return \Vich\UploaderBundle\Mapping\PropertyMapping The property. */ - protected function getPropertyMappingMock($inject_on_load_enabled = true) + protected function getPropertyMappingMock($injectOnLoadEnabled = true) { $mapping = $this->getMockBuilder('Vich\UploaderBundle\Mapping\PropertyMapping') ->disableOriginalConstructor() @@ -214,7 +214,7 @@ protected function getPropertyMappingMock($inject_on_load_enabled = true) $mapping ->expects($this->once()) ->method('getInjectOnLoad') - ->will($this->returnValue($inject_on_load_enabled)); + ->will($this->returnValue($injectOnLoadEnabled)); return $mapping; } diff --git a/Tests/Metadata/Driver/YamlTest.php b/Tests/Metadata/Driver/YamlTest.php index 5eb08f76..0986506c 100644 --- a/Tests/Metadata/Driver/YamlTest.php +++ b/Tests/Metadata/Driver/YamlTest.php @@ -20,7 +20,7 @@ public function testInconsistentYamlFile() $rClass = new \ReflectionClass('\DateTime'); $driver = $this->getDriver($rClass); - $driver->mapping_content = array(); + $driver->mappingContent = array(); $driver->loadMetadataForClass($rClass); } @@ -33,7 +33,7 @@ public function testLoadMetadataForClass($mapping, $expectedMetadata) $rClass = new \ReflectionClass('\DateTime'); $driver = $this->getDriver($rClass); - $driver->mapping_content = array( + $driver->mappingContent = array( $rClass->name => $mapping ); @@ -111,10 +111,10 @@ public function fieldsProvider() class TestableYaml extends Yaml { - public $mapping_content; + public $mappingContent; protected function loadMappingFile($file) { - return $this->mapping_content; + return $this->mappingContent; } } From 74967ab9c826e143bb21bb00df47c3bba1678260 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Tue, 24 Dec 2013 12:31:18 +0000 Subject: [PATCH 31/54] Cleaned a bit the PropertyMappingFactory test --- Tests/Mapping/PropertyMappingFactoryTest.php | 164 +++++++------------ 1 file changed, 61 insertions(+), 103 deletions(-) diff --git a/Tests/Mapping/PropertyMappingFactoryTest.php b/Tests/Mapping/PropertyMappingFactoryTest.php index fcacd8e4..349cd0f1 100644 --- a/Tests/Mapping/PropertyMappingFactoryTest.php +++ b/Tests/Mapping/PropertyMappingFactoryTest.php @@ -27,6 +27,11 @@ class PropertyMappingFactoryTest extends \PHPUnit_Framework_TestCase */ protected $adapter; + /** + * @var DummyEntity + */ + protected $object; + /** * Sets up the test. */ @@ -35,20 +40,22 @@ public function setUp() $this->container = $this->getContainerMock(); $this->metadata = $this->getMetadataReaderMock(); $this->adapter = $this->getAdapterMock(); + + $this->object = new DummyEntity(); } /** - * Tests that an exception is thrown if a non uploadable - * object is passed in. + * Tests that an exception is thrown if a non uploadable object is passed. * - * @expectedException \InvalidArgumentException + * @expectedException InvalidArgumentException + * @expectedExceptionMessage The object is not uploadable. */ public function testFromObjectThrowsExceptionIfNotUploadable() { $this->adapter ->expects($this->once()) ->method('getClassName') - ->will($this->returnValue('StdClass')); + ->will($this->returnValue('stdClass')); $this->metadata ->expects($this->once()) @@ -56,43 +63,46 @@ public function testFromObjectThrowsExceptionIfNotUploadable() ->will($this->returnValue(false)); $factory = new PropertyMappingFactory($this->container, $this->metadata, $this->adapter, array()); - $factory->fromObject(new \StdClass()); + $factory->fromObject(new \stdClass()); } /** - * Test the fromObject method with one uploadable - * field. + * @dataProvider uploadableClassNameProvider */ - public function testFromObjectOneField() + public function testFromObjectWithValidMapping($givenClassName, $inferredClassName) { - $obj = new DummyEntity(); - $mappings = array( 'dummy_file' => array( - 'upload_destination' => 'images', - 'delete_on_remove' => true, - 'delete_on_update' => true, - 'namer' => null, - 'inject_on_load' => true, - 'directory_namer' => null + 'upload_destination' => 'images', + 'delete_on_remove' => true, + 'delete_on_update' => true, + 'namer' => null, + 'inject_on_load' => true, + 'directory_namer' => null ) ); - $this->adapter - ->expects($this->once()) - ->method('getClassName') - ->will($this->returnValue('Vich\UploaderBundle\Tests\DummyEntity')); + if ($givenClassName === null) { + $this->adapter + ->expects($this->once()) + ->method('getClassName') + ->will($this->returnValue($inferredClassName)); + } else { + $this->adapter + ->expects($this->never()) + ->method('getClassName'); + } $this->metadata ->expects($this->once()) ->method('isUploadable') - ->with('Vich\UploaderBundle\Tests\DummyEntity') + ->with($inferredClassName) ->will($this->returnValue(true)); $this->metadata ->expects($this->once()) ->method('getUploadableFields') - ->with('Vich\UploaderBundle\Tests\DummyEntity') + ->with($inferredClassName) ->will($this->returnValue(array( 'file' => array( 'mapping' => 'dummy_file', @@ -102,7 +112,7 @@ public function testFromObjectOneField() ))); $factory = new PropertyMappingFactory($this->container, $this->metadata, $this->adapter, $mappings); - $mappings = $factory->fromObject($obj); + $mappings = $factory->fromObject($this->object, $givenClassName); $this->assertEquals(1, count($mappings)); @@ -116,72 +126,26 @@ public function testFromObjectOneField() $this->assertTrue($mapping->getInjectOnLoad()); } - /** - * Test the fromObject method with one uploadable - * field, with the object classname given. - */ - public function testFromObjectOneFieldWithClassName() + public function uploadableClassNameProvider() { - $obj = new DummyEntity(); + $uploadableClassName = 'Vich\UploaderBundle\Tests\DummyEntity'; - $mappings = array( - 'dummy_file' => array( - 'upload_destination' => 'images', - 'delete_on_remove' => true, - 'delete_on_update' => true, - 'namer' => null, - 'inject_on_load' => true, - 'directory_namer' => null - ) + return array( + // given className, inferred className + array( null, $uploadableClassName), + array( $uploadableClassName, $uploadableClassName), ); - - $this->adapter - ->expects($this->never()) - ->method('getClassName'); - - $this->metadata - ->expects($this->once()) - ->method('isUploadable') - ->with('Vich\UploaderBundle\Tests\DummyEntity') - ->will($this->returnValue(true)); - - $this->metadata - ->expects($this->once()) - ->method('getUploadableFields') - ->with('Vich\UploaderBundle\Tests\DummyEntity') - ->will($this->returnValue(array( - 'file' => array( - 'mapping' => 'dummy_file', - 'propertyName' => 'file', - 'fileNameProperty' => 'fileName', - ) - ))); - - $factory = new PropertyMappingFactory($this->container, $this->metadata, $this->adapter, $mappings); - $mappings = $factory->fromObject($obj, 'Vich\UploaderBundle\Tests\DummyEntity'); - - $this->assertEquals(1, count($mappings)); - - $mapping = $mappings[0]; - - $this->assertEquals('dummy_file', $mapping->getMappingName()); - $this->assertEquals('images', $mapping->getUploadDir()); - $this->assertNull($mapping->getNamer()); - $this->assertFalse($mapping->hasNamer()); - $this->assertTrue($mapping->getDeleteOnRemove()); - $this->assertTrue($mapping->getInjectOnLoad()); } /** * Test that an exception is thrown when an invalid mapping name * is specified. * - * @expectedException \InvalidArgumentException + * @expectedException InvalidArgumentException + * @expectedExceptionMessage No mapping named "dummy_file" configured. */ public function testThrowsExceptionOnInvalidMappingName() { - $obj = new DummyEntity(); - $mappings = array( 'bad_name' => array() ); @@ -210,17 +174,15 @@ public function testThrowsExceptionOnInvalidMappingName() ))); $factory = new PropertyMappingFactory($this->container, $this->metadata, $this->adapter, $mappings); - $factory->fromObject($obj); + $factory->fromObject($this->object); } /** - * Test that the fromField method returns null when an invalid - * field name is specified. + * Test that the fromField method returns null when an invalid field name + * is specified. */ public function testFromFieldReturnsNullOnInvalidFieldName() { - $obj = new DummyEntity(); - $this->adapter ->expects($this->once()) ->method('getClassName') @@ -239,23 +201,21 @@ public function testFromFieldReturnsNullOnInvalidFieldName() ->will($this->returnValue(null)); $factory = new PropertyMappingFactory($this->container, $this->metadata, $this->adapter, array()); - $mapping = $factory->fromField($obj, 'oops'); + $mapping = $factory->fromField($this->object, 'oops'); $this->assertNull($mapping); } public function testConfiguredNamerRetrievedFromContainer() { - $obj = new DummyEntity(); - $mappings = array( 'dummy_file' => array( - 'upload_destination' => 'images', - 'delete_on_remove' => true, - 'delete_on_update' => true, - 'namer' => 'my.custom.namer', - 'inject_on_load' => true, - 'directory_namer' => null + 'upload_destination' => 'images', + 'delete_on_remove' => true, + 'delete_on_update' => true, + 'namer' => 'my.custom.namer', + 'inject_on_load' => true, + 'directory_namer' => null ) ); @@ -291,16 +251,14 @@ public function testConfiguredNamerRetrievedFromContainer() ))); $factory = new PropertyMappingFactory($this->container, $this->metadata, $this->adapter, $mappings); - $mappings = $factory->fromObject($obj); + $mappings = $factory->fromObject($this->object); $this->assertEquals(1, count($mappings)); - if (count($mappings) > 0) { - $mapping = $mappings[0]; + $mapping = $mappings[0]; - $this->assertEquals($namer, $mapping->getNamer()); - $this->assertTrue($mapping->hasNamer()); - } + $this->assertEquals($namer, $mapping->getNamer()); + $this->assertTrue($mapping->hasNamer()); } /** @@ -311,8 +269,8 @@ public function testConfiguredNamerRetrievedFromContainer() protected function getContainerMock() { return $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface') - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); } /** @@ -323,8 +281,8 @@ protected function getContainerMock() protected function getMetadataReaderMock() { return $this->getMockBuilder('Vich\UploaderBundle\Metadata\MetadataReader') - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); } /** @@ -335,7 +293,7 @@ protected function getMetadataReaderMock() protected function getAdapterMock() { return $this->getMockBuilder('Vich\UploaderBundle\Adapter\AdapterInterface') - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); } } From f79203cbf8a6976a93d9e2e5f57e9da06c74dbd8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Tue, 24 Dec 2013 12:45:03 +0000 Subject: [PATCH 32/54] Cleaned the DoctrineUploaderListener test --- .../DoctrineUploaderListenerTest.php | 229 ++++++------------ 1 file changed, 68 insertions(+), 161 deletions(-) diff --git a/Tests/EventListener/DoctrineUploaderListenerTest.php b/Tests/EventListener/DoctrineUploaderListenerTest.php index 91946ae7..b1073496 100644 --- a/Tests/EventListener/DoctrineUploaderListenerTest.php +++ b/Tests/EventListener/DoctrineUploaderListenerTest.php @@ -27,6 +27,21 @@ class DoctrineUploaderListenerTest extends \PHPUnit_Framework_TestCase */ protected $handler; + /** + * @var EventArgs + */ + protected $event; + + /** + * @var DummyEntity + */ + protected $object; + + /** + * @var DoctrineUploaderListener + */ + protected $listener; + /** * Sets up the test */ @@ -35,6 +50,23 @@ public function setUp() $this->adapter = $this->getAdapterMock(); $this->metadata = $this->getMetadataReaderMock(); $this->handler = $this->getHandlerMock(); + $this->object = new DummyEntity(); + $this->event = $this->getEventMock(); + + // the adapter is always used to return the object + $this->adapter + ->expects($this->any()) + ->method('getObjectFromEvent') + ->with($this->event) + ->will($this->returnValue($this->object)); + + // in these tests, the adapter is always used with the same object + $this->adapter + ->expects($this->any()) + ->method('getClassName') + ->will($this->returnValue(get_class($this->object))); + + $this->listener = new DoctrineUploaderListener($this->adapter, $this->metadata, $this->handler); } /** @@ -42,13 +74,12 @@ public function setUp() */ public function testGetSubscribedEvents() { - $listener = new DoctrineUploaderListener($this->adapter, $this->metadata, $this->handler); - $events = $listener->getSubscribedEvents(); + $events = $this->listener->getSubscribedEvents(); - $this->assertTrue(in_array('prePersist', $events)); - $this->assertTrue(in_array('preUpdate', $events)); - $this->assertTrue(in_array('postLoad', $events)); - $this->assertTrue(in_array('postRemove', $events)); + $this->assertContains('prePersist', $events); + $this->assertContains('preUpdate', $events); + $this->assertContains('postLoad', $events); + $this->assertContains('postRemove', $events); } /** @@ -56,22 +87,6 @@ public function testGetSubscribedEvents() */ public function testPrePersist() { - $obj = new DummyEntity(); - - $args = $this->getMockBuilder('Doctrine\Common\EventArgs') - ->disableOriginalConstructor() - ->getMock(); - - $this->adapter - ->expects($this->once()) - ->method('getObjectFromEvent') - ->will($this->returnValue($obj)); - - $this->adapter - ->expects($this->once()) - ->method('getClassName') - ->will($this->returnValue('Vich\UploaderBundle\Tests\DummyEntity')); - $this->metadata ->expects($this->once()) ->method('isUploadable') @@ -81,10 +96,9 @@ public function testPrePersist() $this->handler ->expects($this->once()) ->method('handleUpload') - ->with($obj); + ->with($this->object); - $listener = new DoctrineUploaderListener($this->adapter, $this->metadata, $this->handler); - $listener->prePersist($args); + $this->listener->prePersist($this->event); } /** @@ -92,22 +106,6 @@ public function testPrePersist() */ public function testPrePersistSkipsNonUploadable() { - $obj = new DummyEntity(); - - $args = $this->getMockBuilder('Doctrine\Common\EventArgs') - ->disableOriginalConstructor() - ->getMock(); - - $this->adapter - ->expects($this->once()) - ->method('getObjectFromEvent') - ->will($this->returnValue($obj)); - - $this->adapter - ->expects($this->once()) - ->method('getClassName') - ->will($this->returnValue('Vich\UploaderBundle\Tests\DummyEntity')); - $this->metadata ->expects($this->once()) ->method('isUploadable') @@ -118,8 +116,7 @@ public function testPrePersistSkipsNonUploadable() ->expects($this->never()) ->method('handleUpload'); - $listener = new DoctrineUploaderListener($this->adapter, $this->metadata, $this->handler); - $listener->prePersist($args); + $this->listener->prePersist($this->event); } /** @@ -127,26 +124,10 @@ public function testPrePersistSkipsNonUploadable() */ public function testPreUpdate() { - $obj = new DummyEntity(); - - $args = $this->getMockBuilder('Doctrine\Common\EventArgs') - ->disableOriginalConstructor() - ->getMock(); - - $this->adapter - ->expects($this->once()) - ->method('getObjectFromEvent') - ->will($this->returnValue($obj)); - - $this->adapter - ->expects($this->once()) - ->method('getClassName') - ->will($this->returnValue('Vich\UploaderBundle\Tests\DummyEntity')); - $this->adapter ->expects($this->once()) ->method('recomputeChangeSet') - ->with($args); + ->with($this->event); $this->metadata ->expects($this->once()) @@ -157,10 +138,9 @@ public function testPreUpdate() $this->handler ->expects($this->once()) ->method('handleUpload') - ->with($obj); + ->with($this->object); - $listener = new DoctrineUploaderListener($this->adapter, $this->metadata, $this->handler); - $listener->preUpdate($args); + $this->listener->preUpdate($this->event); } /** @@ -168,22 +148,6 @@ public function testPreUpdate() */ public function testPreUpdateSkipsNonUploadable() { - $obj = new DummyEntity(); - - $args = $this->getMockBuilder('Doctrine\Common\EventArgs') - ->disableOriginalConstructor() - ->getMock(); - - $this->adapter - ->expects($this->once()) - ->method('getObjectFromEvent') - ->will($this->returnValue($obj)); - - $this->adapter - ->expects($this->once()) - ->method('getClassName') - ->will($this->returnValue('Vich\UploaderBundle\Tests\DummyEntity')); - $this->metadata ->expects($this->once()) ->method('isUploadable') @@ -198,8 +162,7 @@ public function testPreUpdateSkipsNonUploadable() ->expects($this->never()) ->method('handleUpload'); - $listener = new DoctrineUploaderListener($this->adapter, $this->metadata, $this->handler); - $listener->preUpdate($args); + $this->listener->preUpdate($this->event); } /** @@ -207,22 +170,6 @@ public function testPreUpdateSkipsNonUploadable() */ public function testPostLoad() { - $obj = new DummyEntity(); - - $args = $this->getMockBuilder('Doctrine\Common\EventArgs') - ->disableOriginalConstructor() - ->getMock(); - - $this->adapter - ->expects($this->once()) - ->method('getObjectFromEvent') - ->will($this->returnValue($obj)); - - $this->adapter - ->expects($this->once()) - ->method('getClassName') - ->will($this->returnValue('Vich\UploaderBundle\Tests\DummyEntity')); - $this->metadata ->expects($this->once()) ->method('isUploadable') @@ -232,10 +179,9 @@ public function testPostLoad() $this->handler ->expects($this->once()) ->method('handleHydration') - ->with($obj); + ->with($this->object); - $listener = new DoctrineUploaderListener($this->adapter, $this->metadata, $this->handler); - $listener->postLoad($args); + $this->listener->postLoad($this->event); } /** @@ -243,22 +189,6 @@ public function testPostLoad() */ public function testPostLoadSkipsNonUploadable() { - $obj = new DummyEntity(); - - $args = $this->getMockBuilder('Doctrine\Common\EventArgs') - ->disableOriginalConstructor() - ->getMock(); - - $this->adapter - ->expects($this->once()) - ->method('getObjectFromEvent') - ->will($this->returnValue($obj)); - - $this->adapter - ->expects($this->once()) - ->method('getClassName') - ->will($this->returnValue('Vich\UploaderBundle\Tests\DummyEntity')); - $this->metadata ->expects($this->once()) ->method('isUploadable') @@ -269,8 +199,7 @@ public function testPostLoadSkipsNonUploadable() ->expects($this->never()) ->method('handleHydration'); - $listener = new DoctrineUploaderListener($this->adapter, $this->metadata, $this->handler); - $listener->postLoad($args); + $this->listener->postLoad($this->event); } /** @@ -278,22 +207,6 @@ public function testPostLoadSkipsNonUploadable() */ public function testPostRemove() { - $obj = new DummyEntity(); - - $args = $this->getMockBuilder('Doctrine\Common\EventArgs') - ->disableOriginalConstructor() - ->getMock(); - - $this->adapter - ->expects($this->once()) - ->method('getObjectFromEvent') - ->will($this->returnValue($obj)); - - $this->adapter - ->expects($this->once()) - ->method('getClassName') - ->will($this->returnValue('Vich\UploaderBundle\Tests\DummyEntity')); - $this->metadata ->expects($this->once()) ->method('isUploadable') @@ -303,10 +216,9 @@ public function testPostRemove() $this->handler ->expects($this->once()) ->method('handleDeletion') - ->with($obj); + ->with($this->object); - $listener = new DoctrineUploaderListener($this->adapter, $this->metadata, $this->handler); - $listener->postRemove($args); + $this->listener->postRemove($this->event); } /** @@ -314,22 +226,6 @@ public function testPostRemove() */ public function testPostRemoveSkipsNonUploadable() { - $obj = new DummyEntity(); - - $args = $this->getMockBuilder('Doctrine\Common\EventArgs') - ->disableOriginalConstructor() - ->getMock(); - - $this->adapter - ->expects($this->once()) - ->method('getObjectFromEvent') - ->will($this->returnValue($obj)); - - $this->adapter - ->expects($this->once()) - ->method('getClassName') - ->will($this->returnValue('Vich\UploaderBundle\Tests\DummyEntity')); - $this->metadata ->expects($this->once()) ->method('isUploadable') @@ -340,8 +236,7 @@ public function testPostRemoveSkipsNonUploadable() ->expects($this->never()) ->method('handleDeletion'); - $listener = new DoctrineUploaderListener($this->adapter, $this->metadata, $this->handler); - $listener->postRemove($args); + $this->listener->postRemove($this->event); } /** @@ -352,8 +247,8 @@ public function testPostRemoveSkipsNonUploadable() protected function getAdapterMock() { return $this->getMockBuilder('Vich\UploaderBundle\Adapter\AdapterInterface') - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); } /** @@ -364,8 +259,8 @@ protected function getAdapterMock() protected function getMetadataReaderMock() { return $this->getMockBuilder('Vich\UploaderBundle\Metadata\MetadataReader') - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); } /** @@ -376,7 +271,19 @@ protected function getMetadataReaderMock() protected function getHandlerMock() { return $this->getMockBuilder('Vich\UploaderBundle\Handler\UploadHandler') - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); + } + + /** + * Creates a mock doctrine event + * + * @return \Doctrine\Common\EventArgs + */ + protected function getEventMock() + { + return $this->getMockBuilder('Doctrine\Common\EventArgs') + ->disableOriginalConstructor() + ->getMock(); } } From ef882a71a4efe3f7ac282d6e199dc7e0b17fd9ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Tue, 24 Dec 2013 14:32:13 +0000 Subject: [PATCH 33/54] Worked on the DirectoryNamers --- Mapping/PropertyMapping.php | 10 +--- Naming/DirectoryNamerInterface.php | 12 +++-- Storage/AbstractStorage.php | 86 ++++++++++++++++-------------- Storage/FileSystemStorage.php | 25 ++++----- Storage/GaufretteStorage.php | 61 +++++++++++---------- 5 files changed, 99 insertions(+), 95 deletions(-) diff --git a/Mapping/PropertyMapping.php b/Mapping/PropertyMapping.php index 80d12c6c..03fdb985 100644 --- a/Mapping/PropertyMapping.php +++ b/Mapping/PropertyMapping.php @@ -208,18 +208,12 @@ public function getFilePropertyName() } /** - * Gets the configured upload directory. + * Returns the raw upload destination, as given in the configuration. * - * @param null $obj - * @param null $field * @return string The configured upload directory. */ - public function getUploadDir($obj = null, $field = null) + public function getUploadDestination() { - if ($this->hasDirectoryNamer()) { - return $this->getDirectoryNamer()->directoryName($obj, $field, $this->mapping['upload_destination']); - } - return $this->mapping['upload_destination']; } diff --git a/Naming/DirectoryNamerInterface.php b/Naming/DirectoryNamerInterface.php index a87a9d8c..0fbdac83 100644 --- a/Naming/DirectoryNamerInterface.php +++ b/Naming/DirectoryNamerInterface.php @@ -2,8 +2,10 @@ namespace Vich\UploaderBundle\Naming; +use Vich\UploaderBundle\Mapping\PropertyMapping; + /** - * NamerInterface. + * DirectoryNamerInterface. * * @author Kevin bond */ @@ -12,10 +14,10 @@ interface DirectoryNamerInterface /** * Creates a directory name for the file being uploaded. * - * @param object $obj The object the upload is attached to. - * @param string $field The name of the uploadable field to generate a name for. - * @param string $uploadDir The upload directory set in config + * @param Propertymapping $mapping The mapping to use to manipulate the given object. + * @param object $object The object the upload is attached to. + * * @return string The directory name. */ - public function directoryName($obj, $field, $uploadDir); + public function name(PropertyMapping $mapping, $object); } diff --git a/Storage/AbstractStorage.php b/Storage/AbstractStorage.php index dc9ad57b..78dc0b57 100644 --- a/Storage/AbstractStorage.php +++ b/Storage/AbstractStorage.php @@ -31,13 +31,31 @@ public function __construct(PropertyMappingFactory $factory) /** * Do real upload * - * @param UploadedFile $file - * @param string $dir - * @param string $name + * @param PropertyMapping $mapping The mapping representing the current object. + * @param UploadedFile $file The file being uploaded. + * @param string $destinationPath The destination path of the file. + */ + abstract protected function doUpload(PropertyMapping $mapping, UploadedFile $file, $destinationPath); + + /** + * Do real remove + * + * @param PropertyMapping $mapping The mapping representing the current object. + * @param string $path The path of the file to remove. + * + * @return boolean Whether the file has been removed or not. + */ + abstract protected function doRemove(PropertyMapping $mapping, $path); + + /** + * Do resolve path * - * @return boolean + * @param string $dir + * @param string $name + * + * @return string */ - abstract protected function doUpload(UploadedFile $file, $dir, $name); + abstract protected function doResolvePath($dir, $path); /** * {@inheritDoc} @@ -52,36 +70,40 @@ public function upload($obj) continue; } + // if there already is a file for the given object, delete it if + // needed if ($mapping->getDeleteOnUpdate() && ($name = $mapping->getFileName($obj))) { - $dir = $mapping->getUploadDir($obj, $mapping->getFilePropertyName()); - - $this->doRemove($dir, $name); + $this->doRemove($mapping, $obj, $name); } + // keep the original name by default + $name = $file->getClientOriginalName(); + + // but use the namer if there is one if ($mapping->hasNamer()) { $name = $mapping->getNamer()->name($mapping, $obj); - } else { - $name = $file->getClientOriginalName(); } - $dir = $mapping->getUploadDir($obj, $mapping->getFilePropertyName()); + // update the filename + $mapping->setFileName($obj, $name); - $this->doUpload($file, $dir, $name); + // determine the upload directory to use + if ($mapping->hasDirectoryNamer()) { + $dir = $mapping->getDirectoryNamer()->name($mapping, $obj); + $name = $dir . DIRECTORY_SEPARATOR . $name; - $mapping->setFileName($obj, $name); + // store the complete path in the filename + // @note: we do this because the FileInjector needs the + // directory, and the DirectoryNamer might need the File object + // to compute it + $mapping->setFileName($obj, $name); + } + + // and finalize the upload + $this->doUpload($mapping, $file, $name); } } - /** - * Do real remove - * - * @param string $dir - * @param string $name - * - * @return boolean - */ - abstract protected function doRemove($dir, $name); - /** * {@inheritDoc} */ @@ -96,36 +118,22 @@ public function remove($obj) } $name = $mapping->getFileName($obj); - if (null === $name) { continue; } - $dir = $mapping->getUploadDir($obj, $mapping->getFilePropertyName()); - - $this->doRemove($dir, $name); + $this->doRemove($mapping, $obj, $name); } } - /** - * Do resolve path - * - * @param string $dir - * @param string $name - * - * @return string - */ - abstract protected function doResolvePath($dir, $name); - /** * {@inheritDoc} */ public function resolvePath($obj, $field, $className = null) { list($mapping, $name) = $this->getFileName($obj, $field, $className); - $dir = $mapping->getUploadDir($obj, $field, $className); - return $this->doResolvePath($dir, $name); + return $this->doResolvePath($mapping->getUploadDestination(), $name); } /** diff --git a/Storage/FileSystemStorage.php b/Storage/FileSystemStorage.php index 08416c08..f1d1e27c 100644 --- a/Storage/FileSystemStorage.php +++ b/Storage/FileSystemStorage.php @@ -4,6 +4,8 @@ use Symfony\Component\HttpFoundation\File\UploadedFile; +use Vich\UploaderBundle\Mapping\PropertyMapping; + /** * FileSystemStorage. * @@ -14,26 +16,20 @@ class FileSystemStorage extends AbstractStorage /** * {@inheritDoc} */ - protected function doUpload(UploadedFile $file, $dir, $name) + protected function doUpload(PropertyMapping $mapping, UploadedFile $file, $destinationPath) { - $uploadDir = $this->getUploadDirectory($dir, $name); - $fileName = basename($name); + $uploadDir = $this->getUploadDirectory($mapping->getUploadDestination(), $destinationPath); + $fileName = basename($destinationPath); return $file->move($uploadDir, $fileName); } /** - * Do real remove - * - * @param string $dir - * @param string $name - * - * @internal param object $obj - * @return boolean + * {@inheritDoc} */ - protected function doRemove($dir, $name) + protected function doRemove(PropertyMapping $mapping, $path) { - $file = $dir . DIRECTORY_SEPARATOR . $name; + $file = $mapping->getUploadDestination() . DIRECTORY_SEPARATOR . $path; return file_exists($file) ? unlink($file) : false; } @@ -53,13 +49,13 @@ public function resolveUri($obj, $field, $className = null) { list($mapping, $name) = $this->getFileName($obj, $field, $className); $uriPrefix = $mapping->getUriPrefix(); - $parts = explode($uriPrefix, $this->convertWindowsDirectorySeparator($mapping->getUploadDir($obj, $field))); - return sprintf('%s/%s', $uriPrefix . array_pop($parts), $name); + return sprintf('%s/%s', $uriPrefix, $this->convertWindowsDirectorySeparator($name)); } /** * @param $string + * * @return string */ protected function convertWindowsDirectorySeparator($string) @@ -75,6 +71,7 @@ protected function convertWindowsDirectorySeparator($string) * * @param $dir * @param $name + * * @return string */ protected function getUploadDirectory($dir, $name) diff --git a/Storage/GaufretteStorage.php b/Storage/GaufretteStorage.php index 15b1e9b8..d887aec5 100644 --- a/Storage/GaufretteStorage.php +++ b/Storage/GaufretteStorage.php @@ -3,15 +3,14 @@ namespace Vich\UploaderBundle\Storage; use Gaufrette\Exception\FileNotFound; -use Vich\UploaderBundle\Mapping\PropertyMappingFactory; - -use Symfony\Component\HttpFoundation\File\UploadedFile; - -use Knp\Bundle\GaufretteBundle\FilesystemMap; - use Gaufrette\Stream\Local as LocalStream; use Gaufrette\StreamMode; use Gaufrette\Adapter\MetadataSupporter; +use Knp\Bundle\GaufretteBundle\FilesystemMap; +use Symfony\Component\HttpFoundation\File\UploadedFile; + +use Vich\UploaderBundle\Mapping\PropertyMapping; +use Vich\UploaderBundle\Mapping\PropertyMappingFactory; /** * GaufretteStorage. @@ -33,9 +32,9 @@ class GaufretteStorage extends AbstractStorage /** * Constructs a new instance of FileSystemStorage. * - * @param \Vich\UploaderBundle\Mapping\PropertyMappingFactory $factory The factory. - * @param FilesystemMap $filesystemMap Gaufrete filesystem factory. - * @param string $protocol Gaufrette stream wrapper protocol. + * @param PropertyMappingFactory $factory The factory. + * @param FilesystemMap $filesystemMap Gaufrete filesystem factory. + * @param string $protocol Gaufrette stream wrapper protocol. */ public function __construct(PropertyMappingFactory $factory, FilesystemMap $filesystemMap, $protocol = 'gaufrette') { @@ -45,31 +44,23 @@ public function __construct(PropertyMappingFactory $factory, FilesystemMap $file $this->protocol = $protocol; } - /** - * Get filesystem adapter by key - * - * @param string $key - * - * @return \Gaufrette\Filesystem - */ - protected function getFilesystem($key) - { - return $this->filesystemMap->get($key); - } - /** * {@inheritDoc} */ - protected function doUpload(UploadedFile $file, $dir, $name) + protected function doUpload(PropertyMapping $mapping, UploadedFile $file, $destinationPath) { - $filesystem = $this->getFilesystem($dir); + $fs = $this->getFilesystem($mapping->getUploadDestination()); - if ($filesystem->getAdapter() instanceof MetadataSupporter) { - $filesystem->getAdapter()->setMetadata($name, array('contentType' => $file->getMimeType())); + if ($fs->getAdapter() instanceof MetadataSupporter) { + $fs->getAdapter()->setMetadata($name, array('contentType' => $file->getMimeType())); } + // just to make sure that $dir is created before we start writing + // @todo: find a better way to do this + $fs->write($destinationPath, 'test'); + $src = new LocalStream($file->getPathname()); - $dst = $filesystem->createStream($name); + $dst = $fs->createStream($destinationPath); $src->open(new StreamMode('rb+')); $dst->open(new StreamMode('wb+')); @@ -86,12 +77,12 @@ protected function doUpload(UploadedFile $file, $dir, $name) /** * {@inheritDoc} */ - protected function doRemove($dir, $name) + protected function doRemove(PropertyMapping $mapping, $path) { - $adapter = $this->getFilesystem($dir); + $fs = $this->getFilesystem($mapping->getUploadDestination()); try { - return $adapter->delete($name); + return $fs->delete($path); } catch (FileNotFound $e) { return false; } @@ -104,4 +95,16 @@ protected function doResolvePath($dir, $name) { return $this->protocol.'://' . $dir . '/' . $name; } + + /** + * Get filesystem adapter by key + * + * @param string $key + * + * @return \Gaufrette\Filesystem + */ + protected function getFilesystem($key) + { + return $this->filesystemMap->get($key); + } } From 667ef480db0e1bb1c9cee0b65655728c83839086 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Tue, 24 Dec 2013 14:47:37 +0000 Subject: [PATCH 34/54] Fixed tests for new DirectoryNamer implementation --- Storage/AbstractStorage.php | 4 +- Storage/FileSystemStorage.php | 3 +- Storage/GaufretteStorage.php | 2 +- Tests/Mapping/PropertyMappingFactoryTest.php | 2 +- Tests/Mapping/PropertyMappingTest.php | 2 +- Tests/Storage/FileSystemStorageTest.php | 45 +++++++++----------- Tests/Storage/GaufretteStorageTest.php | 18 +++----- 7 files changed, 33 insertions(+), 43 deletions(-) diff --git a/Storage/AbstractStorage.php b/Storage/AbstractStorage.php index 78dc0b57..5a2cb2cb 100644 --- a/Storage/AbstractStorage.php +++ b/Storage/AbstractStorage.php @@ -73,7 +73,7 @@ public function upload($obj) // if there already is a file for the given object, delete it if // needed if ($mapping->getDeleteOnUpdate() && ($name = $mapping->getFileName($obj))) { - $this->doRemove($mapping, $obj, $name); + $this->doRemove($mapping, $name); } // keep the original name by default @@ -122,7 +122,7 @@ public function remove($obj) continue; } - $this->doRemove($mapping, $obj, $name); + $this->doRemove($mapping, $name); } } diff --git a/Storage/FileSystemStorage.php b/Storage/FileSystemStorage.php index f1d1e27c..4e407307 100644 --- a/Storage/FileSystemStorage.php +++ b/Storage/FileSystemStorage.php @@ -49,8 +49,9 @@ public function resolveUri($obj, $field, $className = null) { list($mapping, $name) = $this->getFileName($obj, $field, $className); $uriPrefix = $mapping->getUriPrefix(); + $parts = explode($uriPrefix, $this->convertWindowsDirectorySeparator($mapping->getUploadDestination())); - return sprintf('%s/%s', $uriPrefix, $this->convertWindowsDirectorySeparator($name)); + return sprintf('%s/%s', $uriPrefix . array_pop($parts), $this->convertWindowsDirectorySeparator($name)); } /** diff --git a/Storage/GaufretteStorage.php b/Storage/GaufretteStorage.php index d887aec5..91f08251 100644 --- a/Storage/GaufretteStorage.php +++ b/Storage/GaufretteStorage.php @@ -52,7 +52,7 @@ protected function doUpload(PropertyMapping $mapping, UploadedFile $file, $desti $fs = $this->getFilesystem($mapping->getUploadDestination()); if ($fs->getAdapter() instanceof MetadataSupporter) { - $fs->getAdapter()->setMetadata($name, array('contentType' => $file->getMimeType())); + $fs->getAdapter()->setMetadata($destinationPath, array('contentType' => $file->getMimeType())); } // just to make sure that $dir is created before we start writing diff --git a/Tests/Mapping/PropertyMappingFactoryTest.php b/Tests/Mapping/PropertyMappingFactoryTest.php index 349cd0f1..29eee296 100644 --- a/Tests/Mapping/PropertyMappingFactoryTest.php +++ b/Tests/Mapping/PropertyMappingFactoryTest.php @@ -119,7 +119,7 @@ public function testFromObjectWithValidMapping($givenClassName, $inferredClassNa $mapping = $mappings[0]; $this->assertEquals('dummy_file', $mapping->getMappingName()); - $this->assertEquals('images', $mapping->getUploadDir()); + $this->assertEquals('images', $mapping->getUploadDestination()); $this->assertNull($mapping->getNamer()); $this->assertFalse($mapping->hasNamer()); $this->assertTrue($mapping->getDeleteOnRemove()); diff --git a/Tests/Mapping/PropertyMappingTest.php b/Tests/Mapping/PropertyMappingTest.php index dc7bb559..fc37e344 100644 --- a/Tests/Mapping/PropertyMappingTest.php +++ b/Tests/Mapping/PropertyMappingTest.php @@ -25,7 +25,7 @@ public function testConfiguredMappingAccess() 'inject_on_load' => true )); - $this->assertEquals('/tmp', $prop->getUploadDir()); + $this->assertEquals('/tmp', $prop->getUploadDestination()); $this->assertTrue($prop->getDeleteOnRemove()); $this->assertTrue($prop->getInjectOnLoad()); } diff --git a/Tests/Storage/FileSystemStorageTest.php b/Tests/Storage/FileSystemStorageTest.php index 274580f9..94333262 100644 --- a/Tests/Storage/FileSystemStorageTest.php +++ b/Tests/Storage/FileSystemStorageTest.php @@ -125,18 +125,7 @@ public function testUploadedFileIsCorrectlyMoved() $this->mapping ->expects($this->once()) - ->method('getFilePropertyName') - ->will($this->returnValue('file')); - - $this->mapping - ->expects($this->once()) - ->method('getDeleteOnUpdate') - ->will($this->returnValue(false)); - - $this->mapping - ->expects($this->once()) - ->method('getUploadDir') - ->with($this->object, 'file') + ->method('getUploadDestination') ->will($this->returnValue('/dir')); $file @@ -176,11 +165,6 @@ public function testFilenameWithDirectoriesIsUploadedToCorrectDirectory($dir, $f ->method('getNamer') ->will($this->returnValue($namer)); - $this->mapping - ->expects($this->once()) - ->method('getFilePropertyName') - ->will($this->returnValue($name)); - $this->mapping ->expects($this->once()) ->method('getFile') @@ -199,8 +183,7 @@ public function testFilenameWithDirectoriesIsUploadedToCorrectDirectory($dir, $f $this->mapping ->expects($this->once()) - ->method('getUploadDir') - ->with($this->object, $name) + ->method('getUploadDestination') ->will($this->returnValue($dir)); $file @@ -231,7 +214,8 @@ public function filenameWithDirectoriesDataProvider() } /** - * @dataProvider removeDataProvider + * @dataProvider removeDataProvider + * @group remove */ public function testRemove($deleteOnRemove, $uploadDir, $fileName) { @@ -257,12 +241,12 @@ public function testRemove($deleteOnRemove, $uploadDir, $fileName) if ($deleteOnRemove && $fileName !== null) { $this->mapping ->expects($this->once()) - ->method('getUploadDir') + ->method('getUploadDestination') ->will($this->returnValue($this->root->url() . DIRECTORY_SEPARATOR . $uploadDir)); } else { $this->mapping ->expects($this->never()) - ->method('getUploadDir'); + ->method('getUploadDestination'); } $this->storage->remove($this->object); @@ -297,7 +281,7 @@ public function testResolvePath() { $this->mapping ->expects($this->once()) - ->method('getUploadDir') + ->method('getUploadDestination') ->will($this->returnValue('/tmp')); $this->mapping ->expects($this->once()) @@ -339,11 +323,11 @@ public function testResolvePathThrowsExceptionOnInvalidFieldName() * @dataProvider resolveUriDataProvider * @group resolveUri */ - public function testResolveUri($uploadDir, $uri) + public function testResolveUri($uploadDir, $file, $uri) { $this->mapping ->expects($this->once()) - ->method('getUploadDir') + ->method('getUploadDestination') ->will($this->returnValue($uploadDir)); $this->mapping @@ -354,7 +338,7 @@ public function testResolveUri($uploadDir, $uri) $this->mapping ->expects($this->once()) ->method('getFileName') - ->will($this->returnValue('file.txt')); + ->will($this->returnValue($file)); $this->factory ->expects($this->once()) @@ -370,18 +354,27 @@ public function resolveUriDataProvider() return array( array( '/abs/path/web/uploads', + 'file.txt', '/uploads/file.txt' ), array( 'c:\abs\path\web\uploads', + 'file.txt', '/uploads/file.txt' ), array( '/abs/path/web/project/web/uploads', + 'file.txt', '/uploads/file.txt' ), + array( + '/abs/path/web/project/web/uploads/foo', + 'custom/dir/file.txt', + '/uploads/foo/custom/dir/file.txt' + ), array( '/abs/path/web/project/web/uploads/custom/dir', + 'file.txt', '/uploads/custom/dir/file.txt' ), ); diff --git a/Tests/Storage/GaufretteStorageTest.php b/Tests/Storage/GaufretteStorageTest.php index 5f20723f..16d417da 100644 --- a/Tests/Storage/GaufretteStorageTest.php +++ b/Tests/Storage/GaufretteStorageTest.php @@ -149,7 +149,7 @@ public function testRemoveSkipsNullFileNameProperty() $mapping ->expects($this->never()) - ->method('getUploadDir'); + ->method('getUploadDestination'); $this->factory ->expects($this->once()) @@ -172,7 +172,7 @@ public function testResolvePath() $mapping ->expects($this->once()) - ->method('getUploadDir') + ->method('getUploadDestination') ->will($this->returnValue('filesystemKey')); $mapping @@ -203,7 +203,7 @@ public function testResolvePathWithChangedProtocol() $mapping ->expects($this->once()) - ->method('getUploadDir') + ->method('getUploadDestination') ->will($this->returnValue('filesystemKey')); $mapping @@ -237,7 +237,7 @@ public function testThatRemoveMethodDoesDeleteFile() ->will($this->returnValue(true)); $mapping ->expects($this->any()) - ->method('getUploadDir') + ->method('getUploadDestination') ->will($this->returnValue('filesystemKey')); $mapping ->expects($this->once()) @@ -282,16 +282,12 @@ public function testRemoveNotFoundFile() ->will($this->returnValue(true)); $mapping ->expects($this->any()) - ->method('getUploadDir') + ->method('getUploadDestination') ->will($this->returnValue('filesystemKey')); $mapping ->expects($this->once()) ->method('getFileName') ->will($this->returnValue('file.txt')); - $mapping - ->expects($this->once()) - ->method('getFilePropertyName') - ->will($this->returnValue('propertyName')); $filesystem = $this->getFilesystemMock(); $filesystem @@ -368,7 +364,7 @@ public function testUploadSetsMetadataWhenUsingMetadataSupporterAdapter() $mapping ->expects($this->once()) - ->method('getUploadDir') + ->method('getUploadDestination') ->will($this->returnValue('filesystemKey')); $filesystem = $this @@ -464,7 +460,7 @@ public function testUploadDoesNotSetMetadataWhenUsingNonMetadataSupporterAdapter $mapping ->expects($this->once()) - ->method('getUploadDir') + ->method('getUploadDestination') ->will($this->returnValue('filesystemKey')); $filesystem = $this From b5baacc8e2c6d1073e86af5c0fd0cbf1f0f6de59 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Tue, 24 Dec 2013 14:49:58 +0000 Subject: [PATCH 35/54] Removed unused var in FileSystemStorage test --- Tests/Storage/FileSystemStorageTest.php | 2 -- 1 file changed, 2 deletions(-) diff --git a/Tests/Storage/FileSystemStorageTest.php b/Tests/Storage/FileSystemStorageTest.php index 94333262..e4b549e7 100644 --- a/Tests/Storage/FileSystemStorageTest.php +++ b/Tests/Storage/FileSystemStorageTest.php @@ -145,8 +145,6 @@ public function testUploadedFileIsCorrectlyMoved() */ public function testFilenameWithDirectoriesIsUploadedToCorrectDirectory($dir, $filename, $expectedDir, $expectedFileName) { - $name = 'lala'; - $file = $this->getMockBuilder('Symfony\Component\HttpFoundation\File\UploadedFile') ->disableOriginalConstructor() ->getMock(); From 40d6ff0815cec218ddf427084b3bc5edff95ee57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Tue, 24 Dec 2013 15:18:15 +0000 Subject: [PATCH 36/54] Added a Xml driver --- Metadata/Driver/Xml.php | 60 ++++++++++++++++++++++++++++++++++++ Resources/config/mapping.xml | 6 +++- 2 files changed, 65 insertions(+), 1 deletion(-) create mode 100644 Metadata/Driver/Xml.php diff --git a/Metadata/Driver/Xml.php b/Metadata/Driver/Xml.php new file mode 100644 index 00000000..37d38e25 --- /dev/null +++ b/Metadata/Driver/Xml.php @@ -0,0 +1,60 @@ + + */ +class Xml extends AbstractFileDriver +{ + protected function loadMetadataFromFile($file, \ReflectionClass $class = null) + { + $previous = libxml_use_internal_errors(true); + $elem = simplexml_load_file($file); + libxml_use_internal_errors($previous); + + if (false === $elem) { + throw new RuntimeException(libxml_get_last_error()); + } + + $className = $this->guessClassName($file, $elem, $class); + $metadata = new ClassMetadata($className); + + foreach ($elem->children() as $field) { + $fieldMetadata = array( + 'mapping' => (string) $field->attributes()->mapping, + 'propertyName' => (string) $field->attributes()->name, + 'fileNameProperty' => (string) $field->attributes()->filename_property, + ); + + $metadata->fields[(string) $field->attributes()->name] = $fieldMetadata; + } + + return $metadata; + } + + /** + * {@inheritDoc} + */ + protected function getExtension() + { + return 'xml'; + } + + protected function guessClassName($file, \SimpleXMLElement $elem, \ReflectionClass $class = null) + { + if ($class === null) { + return (string) $elem->attributes()->class; + } + + if ($class->name !== (string) $elem->attributes()->class) { + throw new \RuntimeException(sprintf('Expected metadata for class %s to be defined in %s.', $class->name, $file)); + } + + return $class->name; + } +} diff --git a/Resources/config/mapping.xml b/Resources/config/mapping.xml index 6a487800..0ff14c3f 100644 --- a/Resources/config/mapping.xml +++ b/Resources/config/mapping.xml @@ -20,11 +20,15 @@ + + + + - + From 9ed75154c009e0085d9f1fe9b35661b0e6359d38 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Tue, 24 Dec 2013 23:44:50 +0000 Subject: [PATCH 37/54] First full event-based implementation --- DependencyInjection/VichUploaderExtension.php | 51 ++++++-- EventListener/Doctrine/BaseListener.php | 51 ++++++++ EventListener/Doctrine/InjectListener.php | 42 +++++++ EventListener/Doctrine/RemoveListener.php | 58 +++++++++ EventListener/Doctrine/UploadListener.php | 58 +++++++++ EventListener/DoctrineUploaderListener.php | 119 ------------------ EventListener/Propel/BaseListener.php | 43 +++++++ EventListener/Propel/InjectListener.php | 39 ++++++ EventListener/Propel/RemoveListener.php | 51 ++++++++ EventListener/Propel/UploadListener.php | 40 ++++++ EventListener/PropelUploaderListener.php | 87 ------------- Handler/UploadHandler.php | 66 ++++++++-- Injector/FileInjector.php | 37 ++---- Injector/FileInjectorInterface.php | 7 +- Mapping/PropertyMappingFactory.php | 29 ++++- Resources/config/injector.xml | 1 - Resources/config/listener.xml | 23 +++- Storage/AbstractStorage.php | 87 +++++-------- Storage/StorageInterface.php | 6 +- 19 files changed, 578 insertions(+), 317 deletions(-) create mode 100644 EventListener/Doctrine/BaseListener.php create mode 100644 EventListener/Doctrine/InjectListener.php create mode 100644 EventListener/Doctrine/RemoveListener.php create mode 100644 EventListener/Doctrine/UploadListener.php delete mode 100644 EventListener/DoctrineUploaderListener.php create mode 100644 EventListener/Propel/BaseListener.php create mode 100644 EventListener/Propel/InjectListener.php create mode 100644 EventListener/Propel/RemoveListener.php create mode 100644 EventListener/Propel/UploadListener.php delete mode 100644 EventListener/PropelUploaderListener.php diff --git a/DependencyInjection/VichUploaderExtension.php b/DependencyInjection/VichUploaderExtension.php index f0c9820a..8ca65300 100644 --- a/DependencyInjection/VichUploaderExtension.php +++ b/DependencyInjection/VichUploaderExtension.php @@ -5,11 +5,13 @@ use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\Alias; use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\DefinitionDecorator; use Symfony\Component\DependencyInjection\Loader\XmlFileLoader; use Symfony\Component\Config\FileLocator; -use Vich\UploaderBundle\DependencyInjection\Configuration; use Symfony\Component\HttpKernel\Kernel; +use Vich\UploaderBundle\DependencyInjection\Configuration; + /** * VichUploaderExtension. * @@ -17,9 +19,6 @@ */ class VichUploaderExtension extends Extension { - /** - * @var array $tagMap - */ protected $tagMap = array( 'orm' => 'doctrine.event_subscriber', 'mongodb' => 'doctrine_mongodb.odm.event_subscriber', @@ -45,22 +44,15 @@ public function load(array $configs, ContainerBuilder $container) $this->loadServicesFiles($container, $config); $this->registerMetadataDirectories($container, $config); $this->registerCacheStrategy($container, $config); + $this->registerEventListeners($container, $config); // define a few parameters $container->setParameter('vich_uploader.driver', $config['db_driver']); $container->setParameter('vich_uploader.mappings', $config['mappings']); $container->setParameter('vich_uploader.storage_service', $config['storage']); - // choose the right listener - if ($config['db_driver'] !== 'propel') { - $container->getDefinition('vich_uploader.listener.uploader.'.$config['db_driver'])->addTag($this->tagMap[$config['db_driver']]); - } - - // define the adapter listener to use + // define the adapter to use $container->setAlias('vich_uploader.adapter', 'vich_uploader.adapter.'.$config['db_driver']); - - // define the event listener to use - $container->setAlias('vich_uploader.listener.uploader', 'vich_uploader.listener.uploader.'.$config['db_driver']); } protected function loadServicesFiles(ContainerBuilder $container, array $config) @@ -84,6 +76,39 @@ protected function loadServicesFiles(ContainerBuilder $container, array $config) } } + protected function registerEventListeners(ContainerBuilder $container, array $config) + { + $driver = $config['db_driver']; + $servicesMap = array( + 'inject_on_load' => 'inject', + 'delete_on_update' => 'remove', + 'delete_on_remove' => 'remove', + ); + + foreach ($config['mappings'] as $name => $mapping) { + foreach ($servicesMap as $configOption => $service) { + if (!$mapping[$configOption]) { + continue; + } + + $definition = $container + ->setDefinition(sprintf('vich_uploader.listener.%s.%s', $service, $name), new DefinitionDecorator(sprintf('vich_uploader.listener.%s.%s', $service, $driver))) + ->replaceArgument(0, $name); + + if (isset($this->tagMap[$driver])) { + $definition->addTag($this->tagMap[$driver]); + } + } + + $definition = $container + ->setDefinition(sprintf('vich_uploader.listener.upload.%s', $name), new DefinitionDecorator(sprintf('vich_uploader.listener.upload.%s', $driver))) + ->replaceArgument(0, $name); + if (isset($this->tagMap[$driver])) { + $definition->addTag($this->tagMap[$driver], array('priority' => -50)); + } + } + } + protected function registerMetadataDirectories(ContainerBuilder $container, array $config) { $bundles = $container->getParameter('kernel.bundles'); diff --git a/EventListener/Doctrine/BaseListener.php b/EventListener/Doctrine/BaseListener.php new file mode 100644 index 00000000..c66df029 --- /dev/null +++ b/EventListener/Doctrine/BaseListener.php @@ -0,0 +1,51 @@ + + */ +abstract class BaseListener +{ + /** + * @var string + */ + protected $mappingName; + + /** + * @var AdapterInterface $adapter + */ + protected $adapter; + + /** + * @var MetadataReader $metadata + */ + protected $metadata; + + /** + * @var UploaderHandler $handler + */ + protected $handler; + + /** + * Constructs a new instance of UploaderListener. + * + * @param string $mapping The mapping name. + * @param AdapterInterface $adapter The adapter. + * @param MetadataReader $metadata The metadata reader. + * @param UploaderHandler $handler The upload handler. + */ + public function __construct($mapping, AdapterInterface $adapter, MetadataReader $metadata, UploadHandler $handler) + { + $this->mapping = $mapping; + $this->adapter = $adapter; + $this->metadata = $metadata; + $this->handler = $handler; + } +} diff --git a/EventListener/Doctrine/InjectListener.php b/EventListener/Doctrine/InjectListener.php new file mode 100644 index 00000000..bed42fed --- /dev/null +++ b/EventListener/Doctrine/InjectListener.php @@ -0,0 +1,42 @@ + + */ +class InjectListener extends BaseListener implements EventSubscriber +{ + /** + * The events the listener is subscribed to. + * + * @return array The array of events. + */ + public function getSubscribedEvents() + { + return array( + 'postLoad', + ); + } + + /** + * Populates uploadable fields from filename properties. + * + * @param EventArgs $event The event. + */ + public function postLoad(EventArgs $event) + { + $object = $this->adapter->getObjectFromEvent($event); + + if ($this->metadata->isUploadable($this->adapter->getClassName($object))) { + $this->handler->handleHydration($object, $this->mapping); + } + } +} diff --git a/EventListener/Doctrine/RemoveListener.php b/EventListener/Doctrine/RemoveListener.php new file mode 100644 index 00000000..ec1cf281 --- /dev/null +++ b/EventListener/Doctrine/RemoveListener.php @@ -0,0 +1,58 @@ + + */ +class RemoveListener extends BaseListener implements EventSubscriber +{ + /** + * The events the listener is subscribed to. + * + * @return array The array of events. + */ + public function getSubscribedEvents() + { + return array( + 'preUpdate', + 'postRemove', + ); + } + + /** + * Update the file and file name if necessary. + * + * @param EventArgs $event The event. + */ + public function preUpdate(EventArgs $event) + { + $object = $this->adapter->getObjectFromEvent($event); + + if ($this->metadata->isUploadable($this->adapter->getClassName($object))) { + $this->handler->handleCleaning($object, $this->mapping); + $this->adapter->recomputeChangeSet($event); + } + } + + /** + * Removes the file if necessary. + * + * @param EventArgs $event The event. + */ + public function postRemove(EventArgs $event) + { + $object = $this->adapter->getObjectFromEvent($event); + + if ($this->metadata->isUploadable($this->adapter->getClassName($object))) { + $this->handler->handleDeletion($object, $this->mapping); + } + } +} diff --git a/EventListener/Doctrine/UploadListener.php b/EventListener/Doctrine/UploadListener.php new file mode 100644 index 00000000..f6806ab4 --- /dev/null +++ b/EventListener/Doctrine/UploadListener.php @@ -0,0 +1,58 @@ + + */ +class UploadListener extends BaseListener implements EventSubscriber +{ + /** + * The events the listener is subscribed to. + * + * @return array The array of events. + */ + public function getSubscribedEvents() + { + return array( + 'prePersist', + 'preUpdate', + ); + } + + /** + * Checks for file to upload. + * + * @param EventArgs $event The event. + */ + public function prePersist(EventArgs $event) + { + $object = $this->adapter->getObjectFromEvent($event); + + if ($this->metadata->isUploadable($this->adapter->getClassName($object))) { + $this->handler->handleUpload($object, $this->mapping); + } + } + + /** + * Update the file and file name if necessary. + * + * @param EventArgs $event The event. + */ + public function preUpdate(EventArgs $event) + { + $object = $this->adapter->getObjectFromEvent($event); + + if ($this->metadata->isUploadable($this->adapter->getClassName($object))) { + $this->handler->handleUpload($object, $this->mapping); + $this->adapter->recomputeChangeSet($event); + } + } +} diff --git a/EventListener/DoctrineUploaderListener.php b/EventListener/DoctrineUploaderListener.php deleted file mode 100644 index 698028f4..00000000 --- a/EventListener/DoctrineUploaderListener.php +++ /dev/null @@ -1,119 +0,0 @@ - - */ -class DoctrineUploaderListener implements EventSubscriber -{ - /** - * @var AdapterInterface $adapter - */ - protected $adapter; - - /** - * @var MetadataReader $metadata - */ - protected $metadata; - - /** - * @var UploaderHandler $handler - */ - protected $handler; - - /** - * Constructs a new instance of UploaderListener. - * - * @param AdapterInterface $adapter The adapter. - * @param MetadataReader $metadata The metadata reader. - * @param UploaderHandler $handler The upload handler. - */ - public function __construct(AdapterInterface $adapter, MetadataReader $metadata, UploadHandler $handler) - { - $this->adapter = $adapter; - $this->metadata = $metadata; - $this->handler = $handler; - } - - /** - * The events the listener is subscribed to. - * - * @return array The array of events. - */ - public function getSubscribedEvents() - { - return array( - 'prePersist', - 'preUpdate', - 'postLoad', - 'postRemove', - ); - } - - /** - * Checks for file to upload. - * - * @param EventArgs $event The event. - */ - public function prePersist(EventArgs $event) - { - $obj = $this->adapter->getObjectFromEvent($event); - - if ($this->metadata->isUploadable($this->adapter->getClassName($obj))) { - $this->handler->handleUpload($obj); - } - } - - /** - * Update the file and file name if necessary. - * - * @param EventArgs $event The event. - */ - public function preUpdate(EventArgs $event) - { - $obj = $this->adapter->getObjectFromEvent($event); - - if ($this->metadata->isUploadable($this->adapter->getClassName($obj))) { - $this->handler->handleUpload($obj); - $this->adapter->recomputeChangeSet($event); - } - } - - /** - * Populates uploadable fields from filename properties. - * - * @param EventArgs $event The event. - */ - public function postLoad(EventArgs $event) - { - $obj = $this->adapter->getObjectFromEvent($event); - - if ($this->metadata->isUploadable($this->adapter->getClassName($obj))) { - $this->handler->handleHydration($obj); - } - } - - /** - * Removes the file if necessary. - * - * @param EventArgs $event The event. - */ - public function postRemove(EventArgs $event) - { - $obj = $this->adapter->getObjectFromEvent($event); - - if ($this->metadata->isUploadable($this->adapter->getClassName($obj))) { - $this->handler->handleDeletion($obj); - } - } -} diff --git a/EventListener/Propel/BaseListener.php b/EventListener/Propel/BaseListener.php new file mode 100644 index 00000000..c86a7b91 --- /dev/null +++ b/EventListener/Propel/BaseListener.php @@ -0,0 +1,43 @@ + + */ +abstract class BaseListener +{ + /** + * @var string + */ + protected $mappingName; + + /** + * @var AdapterInterface $adapter + */ + protected $adapter; + + /** + * @var UploaderHandler $handler + */ + protected $handler; + + /** + * Constructs a new instance of BaseListener. + * + * @param string $mapping The mapping name. + * @param AdapterInterface $adapter The adapter. + * @param UploaderHandler $handler The upload handler. + */ + public function __construct($mapping, AdapterInterface $adapter, UploadHandler $handler) + { + $this->mapping = $mapping; + $this->adapter = $adapter; + $this->handler = $handler; + } +} diff --git a/EventListener/Propel/InjectListener.php b/EventListener/Propel/InjectListener.php new file mode 100644 index 00000000..2ec2d8da --- /dev/null +++ b/EventListener/Propel/InjectListener.php @@ -0,0 +1,39 @@ + + */ +class InjectListener extends BaseListener implements EventSubscriberInterface +{ + /** + * The events the listener is subscribed to. + * + * @return array The array of events. + */ + public function getSubscribedEvents() + { + return array( + 'propel.post_hydrate' => 'onHydrate', + ); + } + + /** + * Populates uploadable fields from filename properties. + * + * @param GenericEvent $event The event. + */ + public function onHydrate(GenericEvent $event) + { + $object = $this->adapter->getObjectFromEvent($event); + $this->handler->handleHydration($object, $this->mapping); + } +} diff --git a/EventListener/Propel/RemoveListener.php b/EventListener/Propel/RemoveListener.php new file mode 100644 index 00000000..0817c6b3 --- /dev/null +++ b/EventListener/Propel/RemoveListener.php @@ -0,0 +1,51 @@ + + */ +class RemoveListener extends BaseListener implements EventSubscriberInterface +{ + /** + * The events the listener is subscribed to. + * + * @return array The array of events. + */ + public function getSubscribedEvents() + { + return array( + 'propel.pre_update' => 'onUpload', + 'propel.post_delete' => 'onDelete', + ); + } + + /** + * Update the file and file name if necessary. + * + * @param GenericEvent $event The event. + */ + public function onUpload(GenericEvent $event) + { + $object = $this->adapter->getObjectFromEvent($event); + $this->handler->handleCleaning($object, $this->mapping); + } + + /** + * Removes the file when the object is deleted. + * + * @param GenericEvent $event The event. + */ + public function onDelete(GenericEvent $event) + { + $object = $this->adapter->getObjectFromEvent($event); + $this->handler->handleDeletion($object, $this->mapping); + } +} diff --git a/EventListener/Propel/UploadListener.php b/EventListener/Propel/UploadListener.php new file mode 100644 index 00000000..d850cfd5 --- /dev/null +++ b/EventListener/Propel/UploadListener.php @@ -0,0 +1,40 @@ + + */ +class UploadListener extends BaseListener implements EventSubscriberInterface +{ + /** + * The events the listener is subscribed to. + * + * @return array The array of events. + */ + public function getSubscribedEvents() + { + return array( + 'propel.pre_insert' => 'onUpload', + 'propel.pre_update' => 'onUpload', + ); + } + + /** + * Update the file and file name if necessary. + * + * @param GenericEvent $event The event. + */ + public function onUpload(GenericEvent $event) + { + $object = $this->adapter->getObjectFromEvent($event); + $this->handler->handleUpload($object, $this->mapping); + } +} diff --git a/EventListener/PropelUploaderListener.php b/EventListener/PropelUploaderListener.php deleted file mode 100644 index 7dad4a28..00000000 --- a/EventListener/PropelUploaderListener.php +++ /dev/null @@ -1,87 +0,0 @@ - - */ -class PropelUploaderListener implements EventSubscriberInterface -{ - /** - * @var AdapterInterface $adapter - */ - protected $adapter; - - /** - * @var UploaderHandler $handler - */ - protected $handler; - - /** - * Constructs a new instance of UploaderListener. - * - * @param AdapterInterface $adapter The adapter. - * @param UploaderHandler $handler The upload handler. - */ - public function __construct(AdapterInterface $adapter, UploadHandler $handler) - { - $this->adapter = $adapter; - $this->handler = $handler; - } - - /** - * The events the listener is subscribed to. - * - * @return array The array of events. - */ - public static function getSubscribedEvents() - { - return array( - 'propel.pre_insert' => 'onUpload', - 'propel.pre_update' => 'onUpload', - 'propel.post_delete' => 'onDelete', - 'propel.post_hydrate' => 'onHydrate', - ); - } - - /** - * Update the file and file name if necessary. - * - * @param GenericEvent $event The event. - */ - public function onUpload(GenericEvent $event) - { - $obj = $this->adapter->getObjectFromEvent($event); - $this->handler->handleUpload($obj); - } - - /** - * Populates uploadable fields from filename properties. - * - * @param GenericEvent $event The event. - */ - public function onHydrate(GenericEvent $event) - { - $obj = $this->adapter->getObjectFromEvent($event); - $this->handler->handleHydration($obj); - } - - /** - * Removes the file when the object is deleted. - * - * @param GenericEvent $event The event. - */ - public function onDelete(GenericEvent $event) - { - $obj = $this->adapter->getObjectFromEvent($event); - $this->handler->handleDeletion($obj); - } -} diff --git a/Handler/UploadHandler.php b/Handler/UploadHandler.php index dcf9e82a..95466914 100644 --- a/Handler/UploadHandler.php +++ b/Handler/UploadHandler.php @@ -2,8 +2,11 @@ namespace Vich\UploaderBundle\Handler; -use Vich\UploaderBundle\Storage\StorageInterface; +use Symfony\Component\HttpFoundation\File\UploadedFile; + use Vich\UploaderBundle\Injector\FileInjectorInterface; +use Vich\UploaderBundle\Mapping\PropertyMappingFactory; +use Vich\UploaderBundle\Storage\StorageInterface; /** * Upload handler. @@ -12,6 +15,11 @@ */ class UploadHandler { + /** + * @var \Vich\UploaderBundle\Mapping\PropertyMappingFactory + */ + protected $factory; + /** * @var \Vich\UploaderBundle\Storage\StorageInterface $storage */ @@ -25,11 +33,13 @@ class UploadHandler /** * Constructs a new instance of UploaderListener. * + * @param \Vich\UploaderBundle\Mapping\PropertyMappingFactory $factory The mapping factory. * @param \Vich\UploaderBundle\Storage\StorageInterface $storage The storage. * @param \Vich\UploaderBundle\Injector\FileInjectorInterface $injector The injector. */ - public function __construct(StorageInterface $storage, FileInjectorInterface $injector) + public function __construct(PropertyMappingFactory $factory, StorageInterface $storage, FileInjectorInterface $injector) { + $this->factory = $factory; $this->storage = $storage; $this->injector = $injector; } @@ -37,19 +47,57 @@ public function __construct(StorageInterface $storage, FileInjectorInterface $in /** * Checks for file to upload. */ - public function handleUpload($obj) + public function handleUpload($object, $mapping) + { + if (!$this->factory->hasMapping($object, $mapping)) { + return; + } + + $mapping = $this->factory->fromName($object, $mapping); + + $this->storage->upload($object, $mapping); + $this->injector->injectFiles($object, $mapping); + } + + /** + * Checks for file to remove before a new upload. + */ + public function handleCleaning($object, $mapping) { - $this->storage->upload($obj); - $this->injector->injectFiles($obj); + if (!$this->factory->hasMapping($object, $mapping)) { + return; + } + + $mapping = $this->factory->fromName($object, $mapping); + $file = $mapping->getFile($object); + + if ($file === null || !($file instanceof UploadedFile)) { + return; + } + + // if there already is a file for the given object, delete it if needed + if ($mapping->getFileName($object)) { + $this->storage->remove($object, $mapping); + } } - public function handleHydration($obj) + public function handleHydration($object, $mapping) { - $this->injector->injectFiles($obj); + if (!$this->factory->hasMapping($object, $mapping)) { + return; + } + + $mapping = $this->factory->fromName($object, $mapping); + $this->injector->injectFiles($object, $mapping); } - public function handleDeletion($obj) + public function handleDeletion($obj, $mapping) { - $this->storage->remove($obj); + if (!$this->factory->hasMapping($object, $mapping)) { + return; + } + + $mapping = $this->factory->fromName($object, $mapping); + $this->storage->remove($object, $mapping); } } diff --git a/Injector/FileInjector.php b/Injector/FileInjector.php index 17e3f823..64e916aa 100644 --- a/Injector/FileInjector.php +++ b/Injector/FileInjector.php @@ -5,7 +5,7 @@ use Symfony\Component\HttpFoundation\File\File; use Vich\UploaderBundle\Injector\FileInjectorInterface; -use Vich\UploaderBundle\Mapping\PropertyMappingFactory; +use Vich\UploaderBundle\Mapping\PropertyMapping; use Vich\UploaderBundle\Storage\StorageInterface; /** @@ -15,11 +15,6 @@ */ class FileInjector implements FileInjectorInterface { - /** - * @var PropertyMappingFactory $factory - */ - protected $factory; - /** * @var StorageInterface */ @@ -28,34 +23,26 @@ class FileInjector implements FileInjectorInterface /** * Constructs a new instance of FileInjector. * - * @param PropertyMappingFactory $factory The factory. - * @param StorageInterface $storage Storage. + * @param StorageInterface $storage Storage. */ - public function __construct(PropertyMappingFactory $factory, StorageInterface $storage) + public function __construct(StorageInterface $storage) { - $this->factory = $factory; $this->storage = $storage; } /** * {@inheritDoc} */ - public function injectFiles($obj) + public function injectFiles($object, PropertyMapping $mapping) { - $mappings = $this->factory->fromObject($obj); - foreach ($mappings as $mapping) { - if (!$mapping->getInjectOnLoad()) { - continue; - } - - $field = $mapping->getFilePropertyName(); - try { - $path = $this->storage->resolvePath($obj, $field); - } catch (\InvalidArgumentException $e) { - continue; - } - - $mapping->setFile($obj, new File($path, false)); + $field = $mapping->getFilePropertyName(); + + try { + $path = $this->storage->resolvePath($object, $field); + } catch (\InvalidArgumentException $e) { + continue; } + + $mapping->setFile($object, new File($path, false)); } } diff --git a/Injector/FileInjectorInterface.php b/Injector/FileInjectorInterface.php index b3d3eb4f..804b56af 100644 --- a/Injector/FileInjectorInterface.php +++ b/Injector/FileInjectorInterface.php @@ -2,6 +2,8 @@ namespace Vich\UploaderBundle\Injector; +use Vich\UploaderBundle\Mapping\PropertyMapping; + /** * FileInjectorInterface. * @@ -14,7 +16,8 @@ interface FileInjectorInterface * with a populated Symfony\Component\HttpFoundation\File\File * instance if the field is configured for injection. * - * @param object $obj The object. + * @param object $object The object. + * @param PropertyMapping $mapping The mapping representing the field to populate. */ - public function injectFiles($obj); + public function injectFiles($object, PropertyMapping $mapping); } diff --git a/Mapping/PropertyMappingFactory.php b/Mapping/PropertyMappingFactory.php index 9690804d..2768ee45 100644 --- a/Mapping/PropertyMappingFactory.php +++ b/Mapping/PropertyMappingFactory.php @@ -37,6 +37,8 @@ class PropertyMappingFactory */ protected $mappings; + protected $cache = array(); + /** * Constructs a new instance of PropertyMappingFactory. * @@ -53,6 +55,24 @@ public function __construct(ContainerInterface $container, MetadataReader $metad $this->mappings = $mappings; } + public function hasMapping($object, $mappingName) + { + $mappings = $this->fromObject($object); + + return isset($mappings[$mappingName]); + } + + public function fromName($object, $mappingName) + { + $mappings = $this->fromObject($object); + + if (!isset($mappings[$mappingName])) { + throw new \RuntimeException(sprintf('Mapping %s does not exist', $mappingName)); + } + + return $mappings[$mappingName]; + } + /** * Creates an array of PropetyMapping objects which contain the * configuration for the uploadable fields in the specified @@ -71,14 +91,19 @@ public function fromObject($obj, $className = null) } $class = $this->getClassName($obj, $className); + + if (isset($this->cache[$class])) { + return $this->cache[$class]; + } + $this->checkUploadable($class); $mappings = array(); foreach ($this->metadata->getUploadableFields($class) as $field => $mappingData) { - $mappings[] = $this->createMapping($obj, $field, $mappingData); + $mappings[$mappingData['mapping']] = $this->createMapping($obj, $field, $mappingData); } - return $mappings; + return $this->cache[$class] = $mappings; } /** diff --git a/Resources/config/injector.xml b/Resources/config/injector.xml index a455a329..ebede39d 100644 --- a/Resources/config/injector.xml +++ b/Resources/config/injector.xml @@ -11,7 +11,6 @@ - diff --git a/Resources/config/listener.xml b/Resources/config/listener.xml index 2b367b08..3343b275 100644 --- a/Resources/config/listener.xml +++ b/Resources/config/listener.xml @@ -6,24 +6,39 @@ + + - + + - + + + + + + + + - - + + + + + + + diff --git a/Storage/AbstractStorage.php b/Storage/AbstractStorage.php index 5a2cb2cb..25bf84b5 100644 --- a/Storage/AbstractStorage.php +++ b/Storage/AbstractStorage.php @@ -60,68 +60,49 @@ abstract protected function doResolvePath($dir, $path); /** * {@inheritDoc} */ - public function upload($obj) + public function upload($object, PropertyMapping $mapping) { - $mappings = $this->factory->fromObject($obj); - foreach ($mappings as $mapping) { - $file = $mapping->getFile($obj); - - if ($file === null || !($file instanceof UploadedFile)) { - continue; - } - - // if there already is a file for the given object, delete it if - // needed - if ($mapping->getDeleteOnUpdate() && ($name = $mapping->getFileName($obj))) { - $this->doRemove($mapping, $name); - } - - // keep the original name by default - $name = $file->getClientOriginalName(); - - // but use the namer if there is one - if ($mapping->hasNamer()) { - $name = $mapping->getNamer()->name($mapping, $obj); - } - - // update the filename - $mapping->setFileName($obj, $name); - - // determine the upload directory to use - if ($mapping->hasDirectoryNamer()) { - $dir = $mapping->getDirectoryNamer()->name($mapping, $obj); - $name = $dir . DIRECTORY_SEPARATOR . $name; - - // store the complete path in the filename - // @note: we do this because the FileInjector needs the - // directory, and the DirectoryNamer might need the File object - // to compute it - $mapping->setFileName($obj, $name); - } - - // and finalize the upload - $this->doUpload($mapping, $file, $name); + $file = $mapping->getFile($object); + + if ($file === null || !($file instanceof UploadedFile)) { + continue; + } + + // keep the original name by default + $name = $file->getClientOriginalName(); + + // but use the namer if there is one + if ($mapping->hasNamer()) { + $name = $mapping->getNamer()->name($mapping, $object); } + + // update the filename + $mapping->setFileName($object, $name); + + // determine the upload directory to use + if ($mapping->hasDirectoryNamer()) { + $dir = $mapping->getDirectoryNamer()->name($mapping, $object); + $name = $dir . DIRECTORY_SEPARATOR . $name; + + // store the complete path in the filename + // @note: we do this because the FileInjector needs the + // directory, and the DirectoryNamer might need the File object + // to compute it + $mapping->setFileName($object, $name); + } + + // and finalize the upload + $this->doUpload($mapping, $file, $name); } /** * {@inheritDoc} */ - public function remove($obj) + public function remove($object, PropertyMapping $mapping) { - $mappings = $this->factory->fromObject($obj); - - /** @var $mapping PropertyMapping */ - foreach ($mappings as $mapping) { - if (!$mapping->getDeleteOnRemove()) { - continue; - } - - $name = $mapping->getFileName($obj); - if (null === $name) { - continue; - } + $name = $mapping->getFileName($object); + if (null !== $name) { $this->doRemove($mapping, $name); } } diff --git a/Storage/StorageInterface.php b/Storage/StorageInterface.php index 96770f35..f539eb75 100644 --- a/Storage/StorageInterface.php +++ b/Storage/StorageInterface.php @@ -2,6 +2,8 @@ namespace Vich\UploaderBundle\Storage; +use Vich\UploaderBundle\Mapping\PropertyMapping; + /** * StorageInterface. * @@ -15,14 +17,14 @@ interface StorageInterface * * @param object $obj The object. */ - public function upload($obj); + public function upload($object, PropertyMapping $mapping); /** * Removes the files associated with the object if configured to do so. * * @param object $obj The object. */ - public function remove($obj); + public function remove($object, PropertyMapping $mapping); /** * Resolves the path for a file based on the specified object and field From 19f1a6aba1a83fcdfcd715aa54a801db17aa125f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Wed, 25 Dec 2013 00:00:21 +0000 Subject: [PATCH 38/54] Cleaned MongoDBAdapter test --- .../ODM/MongoDB/MongoDBAdapterTest.php | 64 ++++++++----------- 1 file changed, 28 insertions(+), 36 deletions(-) diff --git a/Tests/Adapter/ODM/MongoDB/MongoDBAdapterTest.php b/Tests/Adapter/ODM/MongoDB/MongoDBAdapterTest.php index 8ca3d7f8..e55d3e7d 100644 --- a/Tests/Adapter/ODM/MongoDB/MongoDBAdapterTest.php +++ b/Tests/Adapter/ODM/MongoDB/MongoDBAdapterTest.php @@ -13,59 +13,51 @@ */ class MongoDBAdapterTest extends \PHPUnit_Framework_TestCase { + public static function setUpBeforeClass() + { + if (!class_exists('Doctrine\ODM\MongoDB\Event\LifecycleEventArgs')) { + self::markTestSkipped('Doctrine\ODM\MongoDB\Event\LifecycleEventArgs does not exist.'); + } + } + /** * Test the getObjectFromEvent method. */ public function testGetObjectFromEvent() { - if (!class_exists('Doctrine\ODM\MongoDB\Event\LifecycleEventArgs')) { - $this->markTestSkipped('Doctrine\ODM\MongoDB\Event\LifecycleEventArgs does not exist.'); - } else { - $entity = $this->getMock('Vich\UploaderBundle\Tests\DummyEntity'); + $entity = $this->getMock('Vich\UploaderBundle\Tests\DummyEntity'); - $args = $this->getMockBuilder('Doctrine\ODM\MongoDB\Event\LifecycleEventArgs') - ->disableOriginalConstructor() - ->getMock(); - $args - ->expects($this->once()) - ->method('getDocument') - ->will($this->returnValue($entity)); + $args = $this->getMockBuilder('Doctrine\ODM\MongoDB\Event\LifecycleEventArgs') + ->disableOriginalConstructor() + ->getMock(); + $args + ->expects($this->once()) + ->method('getDocument') + ->will($this->returnValue($entity)); - $adapter = new MongoDBAdapter(); + $adapter = new MongoDBAdapter(); - $this->assertEquals($entity, $adapter->getObjectFromEvent($args)); - } + $this->assertEquals($entity, $adapter->getObjectFromEvent($args)); } /** - * Tests the getReflectionClass method. + * @dataProvider entityProvider */ - public function testGetClassName() + public function testGetClassName($entity, $expectedClassName) { - if (!interface_exists('Doctrine\ODM\MongoDB\Proxy\Proxy')) { - $this->markTestSkipped('Doctrine\ODM\MongoDB\Proxy\Proxy does not exist.'); - } else { - $obj = new DummyEntity(); - $adapter = new MongoDBAdapter(); - $class = $adapter->getClassName($obj); + $adapter = new MongoDBAdapter(); - $this->assertEquals('Vich\UploaderBundle\Tests\DummyEntity', $class); - } + $this->assertEquals($expectedClassName, $adapter->getClassName($entity)); } - /** - * Tests the getReflectionClass method with a proxy. - */ - public function testGetClassNameWithProxy() + public function entityProvider() { - if (!interface_exists('Doctrine\ODM\MongoDB\Proxy\Proxy')) { - $this->markTestSkipped('Doctrine\ODM\MongoDB\Proxy\Proxy does not exist.'); - } else { - $obj = new DummyEntityProxyMongo(); - $adapter = new MongoDBAdapter(); - $class = $adapter->getClassName($obj); + $classicEntity = new DummyEntity(); + $proxiedEntity = new DummyEntityProxyMongo(); - $this->assertEquals('Vich\UploaderBundle\Tests\DummyEntity', $class); - } + return array( + array($classicEntity, 'Vich\UploaderBundle\Tests\DummyEntity'), + array($proxiedEntity, 'Vich\UploaderBundle\Tests\DummyEntity'), + ); } } From 1e2f81de06aee1ba77c97e83a0e87bf52cce6fee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Wed, 25 Dec 2013 00:00:33 +0000 Subject: [PATCH 39/54] Few fixes --- Adapter/ODM/MongoDB/MongoDBAdapter.php | 3 --- Adapter/ORM/DoctrineORMAdapter.php | 3 --- Adapter/Propel/PropelAdapter.php | 2 -- Metadata/Driver/AbstractFileDriver.php | 4 ++-- Metadata/Driver/FileLocator.php | 13 +++++-------- Metadata/MetadataReader.php | 4 +--- 6 files changed, 8 insertions(+), 21 deletions(-) diff --git a/Adapter/ODM/MongoDB/MongoDBAdapter.php b/Adapter/ODM/MongoDB/MongoDBAdapter.php index 3c4c34b3..12e4a61e 100644 --- a/Adapter/ODM/MongoDB/MongoDBAdapter.php +++ b/Adapter/ODM/MongoDB/MongoDBAdapter.php @@ -17,8 +17,6 @@ class MongoDBAdapter implements AdapterInterface */ public function getObjectFromEvent($event) { - /* @var $event \Doctrine\Common\EventArgs */ - return $event->getDocument(); } @@ -27,7 +25,6 @@ public function getObjectFromEvent($event) */ public function recomputeChangeSet($event) { - /* @var $event \Doctrine\Common\EventArgs */ $object = $this->getObjectFromEvent($event); $dm = $event->getDocumentManager(); diff --git a/Adapter/ORM/DoctrineORMAdapter.php b/Adapter/ORM/DoctrineORMAdapter.php index 38d70c00..024124c1 100644 --- a/Adapter/ORM/DoctrineORMAdapter.php +++ b/Adapter/ORM/DoctrineORMAdapter.php @@ -17,8 +17,6 @@ class DoctrineORMAdapter implements AdapterInterface */ public function getObjectFromEvent($event) { - /* @var $event \Doctrine\Common\EventArgs */ - return $event->getEntity(); } @@ -27,7 +25,6 @@ public function getObjectFromEvent($event) */ public function recomputeChangeSet($event) { - /* @var $event \Doctrine\Common\EventArgs */ $object = $this->getObjectFromEvent($event); $em = $event->getEntityManager(); diff --git a/Adapter/Propel/PropelAdapter.php b/Adapter/Propel/PropelAdapter.php index 1faf80c3..12434586 100644 --- a/Adapter/Propel/PropelAdapter.php +++ b/Adapter/Propel/PropelAdapter.php @@ -16,8 +16,6 @@ class PropelAdapter implements AdapterInterface */ public function getObjectFromEvent($event) { - /* @var $event \Symfony\Component\EventDispatcher\GenericEvent */ - return $event->getSubject(); } diff --git a/Metadata/Driver/AbstractFileDriver.php b/Metadata/Driver/AbstractFileDriver.php index 4c02c2ba..061dffa0 100644 --- a/Metadata/Driver/AbstractFileDriver.php +++ b/Metadata/Driver/AbstractFileDriver.php @@ -14,9 +14,9 @@ abstract class AbstractFileDriver implements AdvancedDriverInterface { /** - * @var FileLocatorInterface|FileLocator + * @var FileLocatorInterface */ - private $locator; + protected $locator; public function __construct(FileLocatorInterface $locator) { diff --git a/Metadata/Driver/FileLocator.php b/Metadata/Driver/FileLocator.php index 28d19acf..98dfae6d 100644 --- a/Metadata/Driver/FileLocator.php +++ b/Metadata/Driver/FileLocator.php @@ -57,14 +57,11 @@ public function findFileForClass(\ReflectionClass $class, $extension) */ public function findAllClasses($extension) { - $files = array(); - $finder = new Finder(); - - foreach ($this->dirs as $dir) { - $results = $finder->files()->in($dir)->name('*.' . $extension); - $files = array_merge(iterator_to_array($results), $files); - } + $files = Finder::create() + ->files() + ->name('*.'.$extension) + ->in($this->dirs); - return array_unique($files); + return iterator_to_array($files); } } diff --git a/Metadata/MetadataReader.php b/Metadata/MetadataReader.php index 21bfd94f..a0203453 100644 --- a/Metadata/MetadataReader.php +++ b/Metadata/MetadataReader.php @@ -37,9 +37,7 @@ public function __construct(MetadataFactoryInterface $reader) */ public function isUploadable($class) { - $metadata = $this->reader->getMetadataForClass($class); - - return $metadata !== null; + return $this->reader->getMetadataForClass($class) !== null; } /** From bb63daf828fbc546c517b1b281c559291961a69a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Wed, 25 Dec 2013 00:22:56 +0000 Subject: [PATCH 40/54] Started to fix tests --- Injector/FileInjector.php | 2 +- Storage/AbstractStorage.php | 2 +- Tests/Fixtures/file.txt | 0 Tests/Injector/FileInjectorTest.php | 119 +--------- Tests/Mapping/PropertyMappingFactoryTest.php | 4 +- Tests/Storage/FileSystemStorageTest.php | 51 ++--- Tests/Storage/GaufretteStorageTest.php | 217 +++++++------------ 7 files changed, 98 insertions(+), 297 deletions(-) delete mode 100644 Tests/Fixtures/file.txt diff --git a/Injector/FileInjector.php b/Injector/FileInjector.php index 64e916aa..db421e6f 100644 --- a/Injector/FileInjector.php +++ b/Injector/FileInjector.php @@ -40,7 +40,7 @@ public function injectFiles($object, PropertyMapping $mapping) try { $path = $this->storage->resolvePath($object, $field); } catch (\InvalidArgumentException $e) { - continue; + return; } $mapping->setFile($object, new File($path, false)); diff --git a/Storage/AbstractStorage.php b/Storage/AbstractStorage.php index 25bf84b5..49f1f86a 100644 --- a/Storage/AbstractStorage.php +++ b/Storage/AbstractStorage.php @@ -65,7 +65,7 @@ public function upload($object, PropertyMapping $mapping) $file = $mapping->getFile($object); if ($file === null || !($file instanceof UploadedFile)) { - continue; + return; } // keep the original name by default diff --git a/Tests/Fixtures/file.txt b/Tests/Fixtures/file.txt deleted file mode 100644 index e69de29b..00000000 diff --git a/Tests/Injector/FileInjectorTest.php b/Tests/Injector/FileInjectorTest.php index 87e8c1dc..e09d4c99 100644 --- a/Tests/Injector/FileInjectorTest.php +++ b/Tests/Injector/FileInjectorTest.php @@ -15,11 +15,6 @@ */ class FileInjectorTest extends \PHPUnit_Framework_TestCase { - /** - * @var \Vich\UploaderBundle\Mapping\PropertyMappingFactory $factory - */ - protected $factory; - /** * @var \Vich\UploaderBundle\Storage\StorageInterface $storage */ @@ -40,7 +35,6 @@ class FileInjectorTest extends \PHPUnit_Framework_TestCase */ public function setUp() { - $this->factory = $this->getMockMappingFactory(); $this->storage = $this->getMockStorage(); $this->root = vfsStream::setup('vich_uploader_bundle', null, array( 'uploads' => array( @@ -49,7 +43,7 @@ public function setUp() ), )); - $this->injector = new FileInjector($this->factory, $this->storage); + $this->injector = new FileInjector($this->storage); } /** @@ -61,10 +55,6 @@ public function testInjectsOneFile() $obj = $this->getMock('Vich\UploaderBundle\Tests\DummyEntity'); $fileMapping = $this->getPropertyMappingMock(); - $fileMapping - ->expects($this->once()) - ->method('getInjectOnLoad') - ->will($this->returnValue(true)); $fileMapping ->expects($this->once()) ->method('getFilePropertyName') @@ -76,89 +66,13 @@ public function testInjectsOneFile() return $file instanceof File; })); - $this->factory - ->expects($this->once()) - ->method('fromObject') - ->with($obj) - ->will($this->returnValue(array($fileMapping))); - $this->storage ->expects($this->once()) ->method('resolvePath') ->with($this->equalTo($obj), $this->equalTo($filePropertyName)) ->will($this->returnValue($this->getUploadDir() . DIRECTORY_SEPARATOR . 'file.txt')); - $this->injector->injectFiles($obj); - } - - /** - * Test inject two files. - */ - public function testInjectTwoFiles() - { - $obj = $this->getMock('Vich\UploaderBundle\Tests\TwoFieldsDummyEntity'); - - $fileMapping = $this->getPropertyMappingMock(); - $fileMapping - ->expects($this->once()) - ->method('getFilePropertyName') - ->will($this->returnValue('file')); - $fileMapping - ->expects($this->once()) - ->method('setFile') - ->with($this->equalTo($obj), $this->callback(function ($file) { - return $file instanceof File; - })); - - $imageMapping = $this->getPropertyMappingMock(); - $imageMapping - ->expects($this->once()) - ->method('getFilePropertyName') - ->will($this->returnValue('image')); - $imageMapping - ->expects($this->once()) - ->method('setFile') - ->with($this->equalTo($obj), $this->callback(function ($file) { - return $file instanceof File; - })); - - $this->factory - ->expects($this->once()) - ->method('fromObject') - ->with($obj) - ->will($this->returnValue(array($fileMapping, $imageMapping))); - - $this->storage - ->expects($this->exactly(2)) - ->method('resolvePath') - ->will($this->onConsecutiveCalls( - $this->getUploadDir() . DIRECTORY_SEPARATOR . 'file.txt', - $this->getUploadDir() . DIRECTORY_SEPARATOR . 'image.png' - )); - - $this->injector->injectFiles($obj); - } - - /** - * Test injection is skipped if inject_on_load is configured - * to false. - */ - public function testInjectionIsSkippedIfNotConfigured() - { - $obj = $this->getMock('Vich\UploaderBundle\Tests\DummyEntity'); - - $fileMapping = $this->getPropertyMappingMock(false); - $fileMapping - ->expects($this->never()) - ->method('setFile'); - - $this->factory - ->expects($this->once()) - ->method('fromObject') - ->with($obj) - ->will($this->returnValue(array($fileMapping))); - - $this->injector->injectFiles($obj); + $this->injector->injectFiles($obj, $fileMapping); } public function testPropertyIsNullWhenFileNamePropertyIsNull() @@ -174,30 +88,12 @@ public function testPropertyIsNullWhenFileNamePropertyIsNull() ->expects($this->never()) ->method('setFile'); - $this->factory - ->expects($this->once()) - ->method('fromObject') - ->with($obj) - ->will($this->returnValue(array($fileMapping))); - $this->storage ->expects($this->once()) ->method('resolvePath') ->will($this->throwException(new \InvalidArgumentException)); - $this->injector->injectFiles($obj); - } - - /** - * Gets a mock mapping factory. - * - * @return \Vich\UploaderBundle\Mapping\PropertyMappingFactory The factory. - */ - protected function getMockMappingFactory() - { - return $this->getMockBuilder('Vich\UploaderBundle\Mapping\PropertyMappingFactory') - ->disableOriginalConstructor() - ->getMock(); + $this->injector->injectFiles($obj, $fileMapping); } /** @@ -207,16 +103,9 @@ protected function getMockMappingFactory() */ protected function getPropertyMappingMock($injectOnLoadEnabled = true) { - $mapping = $this->getMockBuilder('Vich\UploaderBundle\Mapping\PropertyMapping') + return $this->getMockBuilder('Vich\UploaderBundle\Mapping\PropertyMapping') ->disableOriginalConstructor() ->getMock(); - - $mapping - ->expects($this->once()) - ->method('getInjectOnLoad') - ->will($this->returnValue($injectOnLoadEnabled)); - - return $mapping; } /** diff --git a/Tests/Mapping/PropertyMappingFactoryTest.php b/Tests/Mapping/PropertyMappingFactoryTest.php index 29eee296..dffa8bdb 100644 --- a/Tests/Mapping/PropertyMappingFactoryTest.php +++ b/Tests/Mapping/PropertyMappingFactoryTest.php @@ -116,7 +116,7 @@ public function testFromObjectWithValidMapping($givenClassName, $inferredClassNa $this->assertEquals(1, count($mappings)); - $mapping = $mappings[0]; + $mapping = $mappings['dummy_file']; $this->assertEquals('dummy_file', $mapping->getMappingName()); $this->assertEquals('images', $mapping->getUploadDestination()); @@ -255,7 +255,7 @@ public function testConfiguredNamerRetrievedFromContainer() $this->assertEquals(1, count($mappings)); - $mapping = $mappings[0]; + $mapping = $mappings['dummy_file']; $this->assertEquals($namer, $mapping->getNamer()); $this->assertTrue($mapping->hasNamer()); diff --git a/Tests/Storage/FileSystemStorageTest.php b/Tests/Storage/FileSystemStorageTest.php index e4b549e7..7e00a826 100644 --- a/Tests/Storage/FileSystemStorageTest.php +++ b/Tests/Storage/FileSystemStorageTest.php @@ -82,7 +82,7 @@ public function testUploadSkipsMappingOnInvalidFile() ->expects($this->never()) ->method('getFileName'); - $this->storage->upload($this->object); + $this->storage->upload($this->object, $this->mapping); } public function invalidFileProvider() @@ -133,7 +133,7 @@ public function testUploadedFileIsCorrectlyMoved() ->method('move') ->with('/dir', 'filename.txt'); - $this->storage->upload($this->object); + $this->storage->upload($this->object, $this->mapping); } @@ -169,11 +169,6 @@ public function testFilenameWithDirectoriesIsUploadedToCorrectDirectory($dir, $f ->with($this->object) ->will($this->returnValue($file)); - $this->mapping - ->expects($this->once()) - ->method('getDeleteOnUpdate') - ->will($this->returnValue(false)); - $this->mapping ->expects($this->once()) ->method('hasNamer') @@ -189,7 +184,7 @@ public function testFilenameWithDirectoriesIsUploadedToCorrectDirectory($dir, $f ->method('move') ->with($expectedDir, $expectedFileName); - $this->storage->upload($this->object); + $this->storage->upload($this->object, $this->mapping); } @@ -215,28 +210,16 @@ public function filenameWithDirectoriesDataProvider() * @dataProvider removeDataProvider * @group remove */ - public function testRemove($deleteOnRemove, $uploadDir, $fileName) + public function testRemove($uploadDir, $fileName) { $this->mapping ->expects($this->once()) - ->method('getDeleteOnRemove') - ->will($this->returnValue($deleteOnRemove)); - - // if the file should be deleted, we'll need its name - if ($deleteOnRemove) { - $this->mapping - ->expects($this->once()) - ->method('getFileName') - ->will($this->returnValue($fileName)); - } else { - $this->mapping - ->expects($this->never()) - ->method('getFileName'); - } + ->method('getFileName') + ->will($this->returnValue($fileName)); // if the file should be deleted and we have its name, then we need the // upload dir - if ($deleteOnRemove && $fileName !== null) { + if ($fileName !== null) { $this->mapping ->expects($this->once()) ->method('getUploadDestination') @@ -247,10 +230,10 @@ public function testRemove($deleteOnRemove, $uploadDir, $fileName) ->method('getUploadDestination'); } - $this->storage->remove($this->object); + $this->storage->remove($this->object, $this->mapping); // the file should have been deleted - if ($deleteOnRemove && $fileName !== null) { + if ($fileName !== null) { $this->assertFalse($this->root->hasChild($uploadDir . DIRECTORY_SEPARATOR . $fileName)); } } @@ -258,15 +241,13 @@ public function testRemove($deleteOnRemove, $uploadDir, $fileName) public function removeDataProvider() { return array( - // deleteOnRemove uploadDir fileName - // don't configured to be deleted upon removal of the entity - array(false, null, null), - // configured, but not file present - array(true, null, null), - // configured and present in the filesystem - array(true, '/uploads', 'test.txt'), - // configured, but file already deleted - array(true, '/uploads', 'file.txt'), + // uploadDir fileName + // no file present + array(null, null), + // present in the filesystem + array('/uploads', 'test.txt'), + // file already deleted + array('/uploads', 'file.txt'), ); } diff --git a/Tests/Storage/GaufretteStorageTest.php b/Tests/Storage/GaufretteStorageTest.php index 16d417da..d5dfcbd2 100644 --- a/Tests/Storage/GaufretteStorageTest.php +++ b/Tests/Storage/GaufretteStorageTest.php @@ -2,8 +2,10 @@ namespace Vich\UploaderBundle\Tests\Storage; -use Vich\UploaderBundle\Storage\GaufretteStorage; use Gaufrette\Exception\FileNotFound; +use org\bovigo\vfs\vfsStream; + +use Vich\UploaderBundle\Storage\GaufretteStorage; use Vich\UploaderBundle\Tests\DummyEntity; /** @@ -23,6 +25,11 @@ class GaufretteStorageTest extends \PHPUnit_Framework_TestCase */ protected $filesystemMap; + /** + * @var vfsStreamDirectory + */ + protected $root; + /** * Sets up the test. */ @@ -30,6 +37,11 @@ public function setUp() { $this->factory = $this->getFactoryMock(); $this->filesystemMap = $this->getFilesystemMapMock(); + $this->root = vfsStream::setup('vich_uploader_bundle', null, array( + 'uploads' => array( + 'file.txt' => 'some content', + ), + )); } /** @@ -42,26 +54,20 @@ public function testUploadSkipsMappingOnNullFile() $mapping = $this->getMappingMock(); $mapping - ->expects($this->once()) - ->method('getFile') - ->will($this->returnValue(null)); + ->expects($this->once()) + ->method('getFile') + ->will($this->returnValue(null)); $mapping - ->expects($this->never()) - ->method('hasNamer'); + ->expects($this->never()) + ->method('hasNamer'); $mapping - ->expects($this->never()) - ->method('getNamer'); - - $this->factory - ->expects($this->once()) - ->method('fromObject') - ->with($obj) - ->will($this->returnValue(array($mapping))); + ->expects($this->never()) + ->method('getNamer'); $storage = new GaufretteStorage($this->factory, $this->filesystemMap); - $storage->upload($obj); + $storage->upload($obj, $mapping); } /** @@ -75,57 +81,24 @@ public function testUploadSkipsMappingOnNonUploadedFileInstance() $mapping = $this->getMappingMock(); $file = $this->getMockBuilder('Symfony\Component\HttpFoundation\File\File') - ->disableOriginalConstructor() - ->getMock(); - - $mapping - ->expects($this->once()) - ->method('getFile') - ->will($this->returnValue($file)); + ->disableOriginalConstructor() + ->getMock(); $mapping - ->expects($this->never()) - ->method('hasNamer'); + ->expects($this->once()) + ->method('getFile') + ->will($this->returnValue($file)); $mapping - ->expects($this->never()) - ->method('getNamer'); - - $this->factory - ->expects($this->once()) - ->method('fromObject') - ->with($obj) - ->will($this->returnValue(array($mapping))); - - $storage = new GaufretteStorage($this->factory, $this->filesystemMap); - $storage->upload($obj); - } - - /** - * Test the remove method does not remove a file that is configured - * to not be deleted upon removal of the entity. - */ - public function testRemoveSkipsConfiguredNotToDeleteOnRemove() - { - $obj = new DummyEntity(); + ->expects($this->never()) + ->method('hasNamer'); - $mapping = $this->getMappingMock(); $mapping - ->expects($this->once()) - ->method('getDeleteOnRemove') - ->will($this->returnValue(false)); - $mapping - ->expects($this->never()) - ->method('getFileName'); - - $this->factory - ->expects($this->once()) - ->method('fromObject') - ->with($obj) - ->will($this->returnValue(array($mapping))); + ->expects($this->never()) + ->method('getNamer'); $storage = new GaufretteStorage($this->factory, $this->filesystemMap); - $storage->remove($obj); + $storage->upload($obj, $mapping); } /** @@ -138,27 +111,16 @@ public function testRemoveSkipsNullFileNameProperty() $mapping = $this->getMappingMock(); $mapping - ->expects($this->once()) - ->method('getDeleteOnRemove') - ->will($this->returnValue(true)); - - $mapping - ->expects($this->once()) - ->method('getFileName') - ->will($this->returnValue(null)); + ->expects($this->once()) + ->method('getFileName') + ->will($this->returnValue(null)); $mapping - ->expects($this->never()) - ->method('getUploadDestination'); - - $this->factory - ->expects($this->once()) - ->method('fromObject') - ->with($obj) - ->will($this->returnValue(array($mapping))); + ->expects($this->never()) + ->method('getUploadDestination'); $storage = new GaufretteStorage($this->factory, $this->filesystemMap); - $storage->remove($obj); + $storage->remove($obj, $mapping); } /** @@ -171,20 +133,20 @@ public function testResolvePath() $mapping = $this->getMappingMock(); $mapping - ->expects($this->once()) - ->method('getUploadDestination') - ->will($this->returnValue('filesystemKey')); + ->expects($this->once()) + ->method('getUploadDestination') + ->will($this->returnValue('filesystemKey')); $mapping - ->expects($this->once()) - ->method('getFileName') - ->will($this->returnValue('file.txt')); + ->expects($this->once()) + ->method('getFileName') + ->will($this->returnValue('file.txt')); $this->factory - ->expects($this->once()) - ->method('fromField') - ->with($obj, 'file') - ->will($this->returnValue($mapping)); + ->expects($this->once()) + ->method('fromField') + ->with($obj, 'file') + ->will($this->returnValue($mapping)); $storage = new GaufretteStorage($this->factory, $this->filesystemMap); $path = $storage->resolvePath($obj, 'file'); @@ -202,20 +164,20 @@ public function testResolvePathWithChangedProtocol() $mapping = $this->getMappingMock(); $mapping - ->expects($this->once()) - ->method('getUploadDestination') - ->will($this->returnValue('filesystemKey')); + ->expects($this->once()) + ->method('getUploadDestination') + ->will($this->returnValue('filesystemKey')); $mapping - ->expects($this->once()) - ->method('getFileName') - ->will($this->returnValue('file.txt')); + ->expects($this->once()) + ->method('getFileName') + ->will($this->returnValue('file.txt')); $this->factory - ->expects($this->once()) - ->method('fromField') - ->with($obj, 'file') - ->will($this->returnValue($mapping)); + ->expects($this->once()) + ->method('fromField') + ->with($obj, 'file') + ->will($this->returnValue($mapping)); $storage = new GaufretteStorage($this->factory, $this->filesystemMap, 'data'); $path = $storage->resolvePath($obj, 'file'); @@ -231,10 +193,6 @@ public function testThatRemoveMethodDoesDeleteFile() $mapping = $this->getMappingMock(); $obj = new DummyEntity(); - $mapping - ->expects($this->once()) - ->method('getDeleteOnRemove') - ->will($this->returnValue(true)); $mapping ->expects($this->any()) ->method('getUploadDestination') @@ -257,15 +215,8 @@ public function testThatRemoveMethodDoesDeleteFile() ->with('filesystemKey') ->will($this->returnValue($filesystem)); - $this - ->factory - ->expects($this->once()) - ->method('fromObject') - ->with($obj) - ->will($this->returnValue(array($mapping))); - $storage = new GaufretteStorage($this->factory, $this->filesystemMap); - $storage->remove($obj); + $storage->remove($obj, $mapping); } /** @@ -276,10 +227,6 @@ public function testRemoveNotFoundFile() $mapping = $this->getMappingMock(); $obj = new DummyEntity(); - $mapping - ->expects($this->once()) - ->method('getDeleteOnRemove') - ->will($this->returnValue(true)); $mapping ->expects($this->any()) ->method('getUploadDestination') @@ -303,15 +250,8 @@ public function testRemoveNotFoundFile() ->with('filesystemKey') ->will($this->returnValue($filesystem)); - $this - ->factory - ->expects($this->once()) - ->method('fromObject') - ->with($obj) - ->will($this->returnValue(array($mapping))); - $storage = new GaufretteStorage($this->factory, $this->filesystemMap); - $storage->remove($obj); + $storage->remove($obj, $mapping); } /** @@ -325,10 +265,10 @@ public function testResolvePathThrowsExceptionOnInvalidFieldName() $obj = new DummyEntity(); $this->factory - ->expects($this->once()) - ->method('fromField') - ->with($obj, 'oops') - ->will($this->returnValue(null)); + ->expects($this->once()) + ->method('fromField') + ->with($obj, 'oops') + ->will($this->returnValue(null)); $storage = new GaufretteStorage($this->factory, $this->filesystemMap); $storage->resolvePath($obj, 'oops'); @@ -355,7 +295,7 @@ public function testUploadSetsMetadataWhenUsingMetadataSupporterAdapter() $file ->expects($this->once()) ->method('getPathname') - ->will($this->returnValue(__DIR__ . '/../Fixtures/file.txt')); + ->will($this->returnValue($this->getUploadDir() . DIRECTORY_SEPARATOR . 'file.txt')); $mapping ->expects($this->once()) @@ -410,13 +350,6 @@ public function testUploadSetsMetadataWhenUsingMetadataSupporterAdapter() ->with('filesystemKey') ->will($this->returnValue($filesystem)); - $this - ->factory - ->expects($this->once()) - ->method('fromObject') - ->with($obj) - ->will($this->returnValue(array($mapping))); - $adapter ->expects($this->once()) ->method('setMetadata') @@ -428,7 +361,7 @@ public function testUploadSetsMetadataWhenUsingMetadataSupporterAdapter() ->will($this->returnValue($adapter)); $storage = new GaufretteStorage($this->factory, $filesystemMap); - $storage->upload($obj); + $storage->upload($obj, $mapping); } public function testUploadDoesNotSetMetadataWhenUsingNonMetadataSupporterAdapter() @@ -451,7 +384,7 @@ public function testUploadDoesNotSetMetadataWhenUsingNonMetadataSupporterAdapter $file ->expects($this->once()) ->method('getPathname') - ->will($this->returnValue(__DIR__ . '/../Fixtures/file.txt')); + ->will($this->returnValue($this->getUploadDir() . DIRECTORY_SEPARATOR . 'file.txt')); $mapping ->expects($this->once()) @@ -506,13 +439,6 @@ public function testUploadDoesNotSetMetadataWhenUsingNonMetadataSupporterAdapter ->with('filesystemKey') ->will($this->returnValue($filesystem)); - $this - ->factory - ->expects($this->once()) - ->method('fromObject') - ->with($obj) - ->will($this->returnValue(array($mapping))); - $adapter ->expects($this->never()) ->method('setMetadata') @@ -524,7 +450,7 @@ public function testUploadDoesNotSetMetadataWhenUsingNonMetadataSupporterAdapter ->will($this->returnValue($adapter)); $storage = new GaufretteStorage($this->factory, $filesystemMap); - $storage->upload($obj); + $storage->upload($obj, $mapping); } /** @@ -569,7 +495,12 @@ protected function getFilesystemMock() protected function getMappingMock() { return $this->getMockBuilder('Vich\UploaderBundle\Mapping\PropertyMapping') - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); + } + + protected function getUploadDir() + { + return $this->root->url() . DIRECTORY_SEPARATOR . 'uploads'; } } From 9ba7bed000f17b6489c4aa6b4e769d8e1859bc46 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Wed, 25 Dec 2013 00:44:34 +0000 Subject: [PATCH 41/54] Deleted useless methods from PropertyMapping --- Mapping/PropertyMapping.php | 34 -------------------- Tests/Mapping/PropertyMappingFactoryTest.php | 8 ----- Tests/Mapping/PropertyMappingTest.php | 7 +--- 3 files changed, 1 insertion(+), 48 deletions(-) diff --git a/Mapping/PropertyMapping.php b/Mapping/PropertyMapping.php index 03fdb985..e93730e5 100644 --- a/Mapping/PropertyMapping.php +++ b/Mapping/PropertyMapping.php @@ -217,40 +217,6 @@ public function getUploadDestination() return $this->mapping['upload_destination']; } - /** - * Determines if the file should be deleted upon removal of the - * entity. - * - * @return bool True if delete on remove, false otherwise. - */ - public function getDeleteOnRemove() - { - return $this->mapping['delete_on_remove']; - } - - /** - * Determines if the file should be deleted when the file is - * replaced by an other one. - * - * @return bool True if delete on update, false otherwise. - */ - public function getDeleteOnUpdate() - { - return $this->mapping['delete_on_update']; - } - - /** - * Determines if the uploadable field should be injected with a - * Symfony\Component\HttpFoundation\File\File instance when - * the object is loaded from the datastore. - * - * @return bool True if the field should be injected, false otherwise. - */ - public function getInjectOnLoad() - { - return $this->mapping['inject_on_load']; - } - /** * Get uri prefix * diff --git a/Tests/Mapping/PropertyMappingFactoryTest.php b/Tests/Mapping/PropertyMappingFactoryTest.php index dffa8bdb..48dbed7f 100644 --- a/Tests/Mapping/PropertyMappingFactoryTest.php +++ b/Tests/Mapping/PropertyMappingFactoryTest.php @@ -74,10 +74,7 @@ public function testFromObjectWithValidMapping($givenClassName, $inferredClassNa $mappings = array( 'dummy_file' => array( 'upload_destination' => 'images', - 'delete_on_remove' => true, - 'delete_on_update' => true, 'namer' => null, - 'inject_on_load' => true, 'directory_namer' => null ) ); @@ -122,8 +119,6 @@ public function testFromObjectWithValidMapping($givenClassName, $inferredClassNa $this->assertEquals('images', $mapping->getUploadDestination()); $this->assertNull($mapping->getNamer()); $this->assertFalse($mapping->hasNamer()); - $this->assertTrue($mapping->getDeleteOnRemove()); - $this->assertTrue($mapping->getInjectOnLoad()); } public function uploadableClassNameProvider() @@ -211,10 +206,7 @@ public function testConfiguredNamerRetrievedFromContainer() $mappings = array( 'dummy_file' => array( 'upload_destination' => 'images', - 'delete_on_remove' => true, - 'delete_on_update' => true, 'namer' => 'my.custom.namer', - 'inject_on_load' => true, 'directory_namer' => null ) ); diff --git a/Tests/Mapping/PropertyMappingTest.php b/Tests/Mapping/PropertyMappingTest.php index fc37e344..5c520376 100644 --- a/Tests/Mapping/PropertyMappingTest.php +++ b/Tests/Mapping/PropertyMappingTest.php @@ -19,14 +19,9 @@ public function testConfiguredMappingAccess() { $prop = new PropertyMapping('file', 'fileName'); $prop->setMapping(array( - 'delete_on_remove' => true, - 'delete_on_update' => true, - 'upload_destination' => '/tmp', - 'inject_on_load' => true + 'upload_destination' => '/tmp', )); $this->assertEquals('/tmp', $prop->getUploadDestination()); - $this->assertTrue($prop->getDeleteOnRemove()); - $this->assertTrue($prop->getInjectOnLoad()); } } From 6467b5a41a960d5cf8a018e0bcff890ada4cce1a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Wed, 25 Dec 2013 11:13:59 +0000 Subject: [PATCH 42/54] Introduced a CachedPropertyMappingFactory class --- Mapping/CachedPropertyMappingFactory.php | 35 ++++++++++++++++++++++++ Mapping/PropertyMappingFactory.php | 9 +----- Resources/config/factory.xml | 6 +++- 3 files changed, 41 insertions(+), 9 deletions(-) create mode 100644 Mapping/CachedPropertyMappingFactory.php diff --git a/Mapping/CachedPropertyMappingFactory.php b/Mapping/CachedPropertyMappingFactory.php new file mode 100644 index 00000000..d3f61330 --- /dev/null +++ b/Mapping/CachedPropertyMappingFactory.php @@ -0,0 +1,35 @@ + + */ +class CachedPropertyMappingFactory extends PropertyMappingFactory +{ + protected $cache = array(); + + public function fromObject($obj, $className = null) + { + $class = $this->getClassName($obj, $className); + + if (isset($this->cache[$class])) { + return $this->cache[$class]; + } + + return $this->cache[$class] = parent::fromObject($obj, $className); + } + + public function fromField($obj, $field, $className = null) + { + $class = $this->getClassName($obj, $className); + + if (isset($this->cache[$class.'::'.$field])) { + return $this->cache[$class.'::'.$field]; + } + + return $this->cache[$class.'::'.$field] = parent::fromField($obj, $field, $className);; + } +} diff --git a/Mapping/PropertyMappingFactory.php b/Mapping/PropertyMappingFactory.php index 2768ee45..f289ec98 100644 --- a/Mapping/PropertyMappingFactory.php +++ b/Mapping/PropertyMappingFactory.php @@ -37,8 +37,6 @@ class PropertyMappingFactory */ protected $mappings; - protected $cache = array(); - /** * Constructs a new instance of PropertyMappingFactory. * @@ -91,11 +89,6 @@ public function fromObject($obj, $className = null) } $class = $this->getClassName($obj, $className); - - if (isset($this->cache[$class])) { - return $this->cache[$class]; - } - $this->checkUploadable($class); $mappings = array(); @@ -103,7 +96,7 @@ public function fromObject($obj, $className = null) $mappings[$mappingData['mapping']] = $this->createMapping($obj, $field, $mappingData); } - return $this->cache[$class] = $mappings; + return $mappings; } /** diff --git a/Resources/config/factory.xml b/Resources/config/factory.xml index 447ded1d..71e15e26 100644 --- a/Resources/config/factory.xml +++ b/Resources/config/factory.xml @@ -4,9 +4,13 @@ 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"> + + Vich\UploaderBundle\Mapping\CachedPropertyMappingFactory + + - + From 46b7a1a15a9334478d87a4c82cd9b54fcd0ac802 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Wed, 25 Dec 2013 15:36:29 +0000 Subject: [PATCH 43/54] Fixed event listeners tests --- DependencyInjection/VichUploaderExtension.php | 2 +- EventListener/Doctrine/CleanListener.php | 43 +++ EventListener/Doctrine/RemoveListener.php | 16 - EventListener/Propel/CleanListener.php | 39 +++ EventListener/Propel/InjectListener.php | 2 +- EventListener/Propel/RemoveListener.php | 16 +- EventListener/Propel/UploadListener.php | 2 +- Resources/config/listener.xml | 5 + .../Doctrine/CleanListenerTest.php | 80 +++++ .../Doctrine/InjectListenerTest.php | 70 +++++ .../Doctrine/ListenerTestCase.php | 119 ++++++++ .../Doctrine/RemoveListenerTest.php | 70 +++++ .../Doctrine/UploadListenerTest.php | 116 +++++++ .../DoctrineUploaderListenerTest.php | 289 ------------------ .../Propel/CleanListenerTest.php | 43 +++ .../Propel/InjectListenerTest.php | 43 +++ .../EventListener/Propel/ListenerTestCase.php | 100 ++++++ .../Propel/RemoveListenerTest.php | 43 +++ .../Propel/UploadListenerTest.php | 44 +++ .../PropelUploaderListenerTest.php | 142 --------- 20 files changed, 820 insertions(+), 464 deletions(-) create mode 100644 EventListener/Doctrine/CleanListener.php create mode 100644 EventListener/Propel/CleanListener.php create mode 100644 Tests/EventListener/Doctrine/CleanListenerTest.php create mode 100644 Tests/EventListener/Doctrine/InjectListenerTest.php create mode 100644 Tests/EventListener/Doctrine/ListenerTestCase.php create mode 100644 Tests/EventListener/Doctrine/RemoveListenerTest.php create mode 100644 Tests/EventListener/Doctrine/UploadListenerTest.php delete mode 100644 Tests/EventListener/DoctrineUploaderListenerTest.php create mode 100644 Tests/EventListener/Propel/CleanListenerTest.php create mode 100644 Tests/EventListener/Propel/InjectListenerTest.php create mode 100644 Tests/EventListener/Propel/ListenerTestCase.php create mode 100644 Tests/EventListener/Propel/RemoveListenerTest.php create mode 100644 Tests/EventListener/Propel/UploadListenerTest.php delete mode 100644 Tests/EventListener/PropelUploaderListenerTest.php diff --git a/DependencyInjection/VichUploaderExtension.php b/DependencyInjection/VichUploaderExtension.php index 8ca65300..d434513c 100644 --- a/DependencyInjection/VichUploaderExtension.php +++ b/DependencyInjection/VichUploaderExtension.php @@ -81,7 +81,7 @@ protected function registerEventListeners(ContainerBuilder $container, array $co $driver = $config['db_driver']; $servicesMap = array( 'inject_on_load' => 'inject', - 'delete_on_update' => 'remove', + 'delete_on_update' => 'clean', 'delete_on_remove' => 'remove', ); diff --git a/EventListener/Doctrine/CleanListener.php b/EventListener/Doctrine/CleanListener.php new file mode 100644 index 00000000..790786be --- /dev/null +++ b/EventListener/Doctrine/CleanListener.php @@ -0,0 +1,43 @@ + + */ +class CleanListener extends BaseListener implements EventSubscriber +{ + /** + * The events the listener is subscribed to. + * + * @return array The array of events. + */ + public function getSubscribedEvents() + { + return array( + 'preUpdate', + ); + } + + /** + * Update the file and file name if necessary. + * + * @param EventArgs $event The event. + */ + public function preUpdate(EventArgs $event) + { + $object = $this->adapter->getObjectFromEvent($event); + + if ($this->metadata->isUploadable($this->adapter->getClassName($object))) { + $this->handler->handleCleaning($object, $this->mapping); + $this->adapter->recomputeChangeSet($event); + } + } +} diff --git a/EventListener/Doctrine/RemoveListener.php b/EventListener/Doctrine/RemoveListener.php index ec1cf281..2024fdab 100644 --- a/EventListener/Doctrine/RemoveListener.php +++ b/EventListener/Doctrine/RemoveListener.php @@ -22,26 +22,10 @@ class RemoveListener extends BaseListener implements EventSubscriber public function getSubscribedEvents() { return array( - 'preUpdate', 'postRemove', ); } - /** - * Update the file and file name if necessary. - * - * @param EventArgs $event The event. - */ - public function preUpdate(EventArgs $event) - { - $object = $this->adapter->getObjectFromEvent($event); - - if ($this->metadata->isUploadable($this->adapter->getClassName($object))) { - $this->handler->handleCleaning($object, $this->mapping); - $this->adapter->recomputeChangeSet($event); - } - } - /** * Removes the file if necessary. * diff --git a/EventListener/Propel/CleanListener.php b/EventListener/Propel/CleanListener.php new file mode 100644 index 00000000..ee8f5b93 --- /dev/null +++ b/EventListener/Propel/CleanListener.php @@ -0,0 +1,39 @@ + + */ +class CleanListener extends BaseListener implements EventSubscriberInterface +{ + /** + * The events the listener is subscribed to. + * + * @return array The array of events. + */ + public static function getSubscribedEvents() + { + return array( + 'propel.pre_update' => 'onUpload', + ); + } + + /** + * Update the file and file name if necessary. + * + * @param GenericEvent $event The event. + */ + public function onUpload(GenericEvent $event) + { + $object = $this->adapter->getObjectFromEvent($event); + $this->handler->handleCleaning($object, $this->mapping); + } +} diff --git a/EventListener/Propel/InjectListener.php b/EventListener/Propel/InjectListener.php index 2ec2d8da..1db4285a 100644 --- a/EventListener/Propel/InjectListener.php +++ b/EventListener/Propel/InjectListener.php @@ -19,7 +19,7 @@ class InjectListener extends BaseListener implements EventSubscriberInterface * * @return array The array of events. */ - public function getSubscribedEvents() + public static function getSubscribedEvents() { return array( 'propel.post_hydrate' => 'onHydrate', diff --git a/EventListener/Propel/RemoveListener.php b/EventListener/Propel/RemoveListener.php index 0817c6b3..8797c478 100644 --- a/EventListener/Propel/RemoveListener.php +++ b/EventListener/Propel/RemoveListener.php @@ -19,25 +19,13 @@ class RemoveListener extends BaseListener implements EventSubscriberInterface * * @return array The array of events. */ - public function getSubscribedEvents() + public static function getSubscribedEvents() { return array( - 'propel.pre_update' => 'onUpload', - 'propel.post_delete' => 'onDelete', + 'propel.post_delete' => 'onDelete', ); } - /** - * Update the file and file name if necessary. - * - * @param GenericEvent $event The event. - */ - public function onUpload(GenericEvent $event) - { - $object = $this->adapter->getObjectFromEvent($event); - $this->handler->handleCleaning($object, $this->mapping); - } - /** * Removes the file when the object is deleted. * diff --git a/EventListener/Propel/UploadListener.php b/EventListener/Propel/UploadListener.php index d850cfd5..8daf34c6 100644 --- a/EventListener/Propel/UploadListener.php +++ b/EventListener/Propel/UploadListener.php @@ -19,7 +19,7 @@ class UploadListener extends BaseListener implements EventSubscriberInterface * * @return array The array of events. */ - public function getSubscribedEvents() + public static function getSubscribedEvents() { return array( 'propel.pre_insert' => 'onUpload', diff --git a/Resources/config/listener.xml b/Resources/config/listener.xml index 3343b275..56e8e460 100644 --- a/Resources/config/listener.xml +++ b/Resources/config/listener.xml @@ -15,12 +15,15 @@ + + + @@ -34,10 +37,12 @@ + + diff --git a/Tests/EventListener/Doctrine/CleanListenerTest.php b/Tests/EventListener/Doctrine/CleanListenerTest.php new file mode 100644 index 00000000..9e3de1d4 --- /dev/null +++ b/Tests/EventListener/Doctrine/CleanListenerTest.php @@ -0,0 +1,80 @@ + + */ +class CleanListenerTest extends ListenerTestCase +{ + /** + * Sets up the test + */ + public function setUp() + { + parent::setUp(); + + $this->listener = new CleanListener(self::MAPPING_NAME, $this->adapter, $this->metadata, $this->handler); + } + + /** + * Test the getSubscribedEvents method. + */ + public function testGetSubscribedEvents() + { + $events = $this->listener->getSubscribedEvents(); + + $this->assertSame(array('preUpdate'), $events); + } + + /** + * Test the preUpdate method. + */ + public function testPreUpdate() + { + $this->metadata + ->expects($this->once()) + ->method('isUploadable') + ->with('Vich\UploaderBundle\Tests\DummyEntity') + ->will($this->returnValue(true)); + + $this->handler + ->expects($this->once()) + ->method('handleCleaning') + ->with($this->object, self::MAPPING_NAME); + + $this->adapter + ->expects($this->once()) + ->method('recomputeChangeSet') + ->with($this->event); + + $this->listener->preUpdate($this->event); + } + + + /** + * Test that preUpdate skips non uploadable entity. + */ + public function testPreUpdateSkipsNonUploadable() + { + $this->metadata + ->expects($this->once()) + ->method('isUploadable') + ->with('Vich\UploaderBundle\Tests\DummyEntity') + ->will($this->returnValue(false)); + + $this->handler + ->expects($this->never()) + ->method('handleCleaning'); + + $this->adapter + ->expects($this->never()) + ->method('recomputeChangeSet'); + + $this->listener->preUpdate($this->event); + } +} diff --git a/Tests/EventListener/Doctrine/InjectListenerTest.php b/Tests/EventListener/Doctrine/InjectListenerTest.php new file mode 100644 index 00000000..a521173f --- /dev/null +++ b/Tests/EventListener/Doctrine/InjectListenerTest.php @@ -0,0 +1,70 @@ + + */ +class InjectListenerTest extends ListenerTestCase +{ + /** + * Sets up the test + */ + public function setUp() + { + parent::setUp(); + + $this->listener = new InjectListener(self::MAPPING_NAME, $this->adapter, $this->metadata, $this->handler); + } + + /** + * Test the getSubscribedEvents method. + */ + public function testGetSubscribedEvents() + { + $events = $this->listener->getSubscribedEvents(); + + $this->assertSame(array('postLoad'), $events); + } + + /** + * Test the postLoad method. + */ + public function testPostLoad() + { + $this->metadata + ->expects($this->once()) + ->method('isUploadable') + ->with('Vich\UploaderBundle\Tests\DummyEntity') + ->will($this->returnValue(true)); + + $this->handler + ->expects($this->once()) + ->method('handleHydration') + ->with($this->object, self::MAPPING_NAME); + + $this->listener->postLoad($this->event); + } + + /** + * Test that postLoad skips non uploadable entity. + */ + public function testPostLoadSkipsNonUploadable() + { + $this->metadata + ->expects($this->once()) + ->method('isUploadable') + ->with('Vich\UploaderBundle\Tests\DummyEntity') + ->will($this->returnValue(false)); + + $this->handler + ->expects($this->never()) + ->method('handleHydration', self::MAPPING_NAME); + + $this->listener->postLoad($this->event); + } +} diff --git a/Tests/EventListener/Doctrine/ListenerTestCase.php b/Tests/EventListener/Doctrine/ListenerTestCase.php new file mode 100644 index 00000000..ab85610e --- /dev/null +++ b/Tests/EventListener/Doctrine/ListenerTestCase.php @@ -0,0 +1,119 @@ + + */ +class ListenerTestCase extends \PHPUnit_Framework_TestCase +{ + const MAPPING_NAME = 'dummy_mapping'; + + /** + * @var \Vich\UploaderBundle\Adapter\AdapterInterface $adapter + */ + protected $adapter; + + /** + * @var \Vich\UploaderBundle\Metadata\MetadataReader $metadata + */ + protected $metadata; + + /** + * @var \Vich\UploaderBundle\Handler\UploadHandler $handler + */ + protected $handler; + + /** + * @var EventArgs + */ + protected $event; + + /** + * @var DummyEntity + */ + protected $object; + + /** + * @var DoctrineUploaderListener + */ + protected $listener; + + /** + * Sets up the test + */ + public function setUp() + { + $this->adapter = $this->getAdapterMock(); + $this->metadata = $this->getMetadataReaderMock(); + $this->handler = $this->getHandlerMock(); + $this->object = new DummyEntity(); + $this->event = $this->getEventMock(); + + // the adapter is always used to return the object + $this->adapter + ->expects($this->any()) + ->method('getObjectFromEvent') + ->with($this->event) + ->will($this->returnValue($this->object)); + + // in these tests, the adapter is always used with the same object + $this->adapter + ->expects($this->any()) + ->method('getClassName') + ->will($this->returnValue(get_class($this->object))); + } + + /** + * Creates a mock adapter. + * + * @return \Vich\UploaderBundle\Adapter\AdapterInterface The mock adapter. + */ + protected function getAdapterMock() + { + return $this->getMockBuilder('Vich\UploaderBundle\Adapter\AdapterInterface') + ->disableOriginalConstructor() + ->getMock(); + } + + /** + * Creates a mock metadata reader. + * + * @return \Vich\UploaderBundle\Metadata\MetadataReader The mock metadata reader. + */ + protected function getMetadataReaderMock() + { + return $this->getMockBuilder('Vich\UploaderBundle\Metadata\MetadataReader') + ->disableOriginalConstructor() + ->getMock(); + } + + /** + * Creates a mock handler. + * + * @return \Vich\UploaderBundle\Handler\UploadHandler The handler mock. + */ + protected function getHandlerMock() + { + return $this->getMockBuilder('Vich\UploaderBundle\Handler\UploadHandler') + ->disableOriginalConstructor() + ->getMock(); + } + + /** + * Creates a mock doctrine event + * + * @return \Doctrine\Common\EventArgs + */ + protected function getEventMock() + { + return $this->getMockBuilder('Doctrine\Common\EventArgs') + ->disableOriginalConstructor() + ->getMock(); + } +} diff --git a/Tests/EventListener/Doctrine/RemoveListenerTest.php b/Tests/EventListener/Doctrine/RemoveListenerTest.php new file mode 100644 index 00000000..2cee136c --- /dev/null +++ b/Tests/EventListener/Doctrine/RemoveListenerTest.php @@ -0,0 +1,70 @@ + + */ +class RemoveListenerTest extends ListenerTestCase +{ + /** + * Sets up the test + */ + public function setUp() + { + parent::setUp(); + + $this->listener = new RemoveListener(self::MAPPING_NAME, $this->adapter, $this->metadata, $this->handler); + } + + /** + * Test the getSubscribedEvents method. + */ + public function testGetSubscribedEvents() + { + $events = $this->listener->getSubscribedEvents(); + + $this->assertSame(array('postRemove'), $events); + } + + /** + * Test the postRemove method. + */ + public function testPostRemove() + { + $this->metadata + ->expects($this->once()) + ->method('isUploadable') + ->with('Vich\UploaderBundle\Tests\DummyEntity') + ->will($this->returnValue(true)); + + $this->handler + ->expects($this->once()) + ->method('handleDeletion') + ->with($this->object, self::MAPPING_NAME); + + $this->listener->postRemove($this->event); + } + + /** + * Test that postRemove skips non uploadable entity. + */ + public function testPostRemoveSkipsNonUploadable() + { + $this->metadata + ->expects($this->once()) + ->method('isUploadable') + ->with('Vich\UploaderBundle\Tests\DummyEntity') + ->will($this->returnValue(false)); + + $this->handler + ->expects($this->never()) + ->method('handleDeletion'); + + $this->listener->postRemove($this->event); + } +} diff --git a/Tests/EventListener/Doctrine/UploadListenerTest.php b/Tests/EventListener/Doctrine/UploadListenerTest.php new file mode 100644 index 00000000..fb3bfc67 --- /dev/null +++ b/Tests/EventListener/Doctrine/UploadListenerTest.php @@ -0,0 +1,116 @@ + + */ +class UploadListenerTest extends ListenerTestCase +{ + /** + * Sets up the test + */ + public function setUp() + { + parent::setUp(); + + $this->listener = new UploadListener(self::MAPPING_NAME, $this->adapter, $this->metadata, $this->handler); + } + + /** + * Test the getSubscribedEvents method. + */ + public function testGetSubscribedEvents() + { + $events = $this->listener->getSubscribedEvents(); + + $this->assertSame(array('prePersist', 'preUpdate'), $events); + } + + /** + * Tests the prePersist method. + */ + public function testPrePersist() + { + $this->metadata + ->expects($this->once()) + ->method('isUploadable') + ->with('Vich\UploaderBundle\Tests\DummyEntity') + ->will($this->returnValue(true)); + + $this->handler + ->expects($this->once()) + ->method('handleUpload') + ->with($this->object, self::MAPPING_NAME); + + $this->listener->prePersist($this->event); + } + + /** + * Tests that prePersist skips non-uploadable entity. + */ + public function testPrePersistSkipsNonUploadable() + { + $this->metadata + ->expects($this->once()) + ->method('isUploadable') + ->with('Vich\UploaderBundle\Tests\DummyEntity') + ->will($this->returnValue(false)); + + $this->handler + ->expects($this->never()) + ->method('handleUpload'); + + $this->listener->prePersist($this->event); + } + + /** + * Test the preUpdate method. + */ + public function testPreUpdate() + { + $this->adapter + ->expects($this->once()) + ->method('recomputeChangeSet') + ->with($this->event); + + $this->metadata + ->expects($this->once()) + ->method('isUploadable') + ->with('Vich\UploaderBundle\Tests\DummyEntity') + ->will($this->returnValue(true)); + + $this->handler + ->expects($this->once()) + ->method('handleUpload') + ->with($this->object, self::MAPPING_NAME); + + $this->listener->preUpdate($this->event); + } + + /** + * Test that preUpdate skips non uploadable entity. + */ + public function testPreUpdateSkipsNonUploadable() + { + $this->metadata + ->expects($this->once()) + ->method('isUploadable') + ->with('Vich\UploaderBundle\Tests\DummyEntity') + ->will($this->returnValue(false)); + + $this->adapter + ->expects($this->never()) + ->method('recomputeChangeSet'); + + $this->handler + ->expects($this->never()) + ->method('handleUpload'); + + $this->listener->preUpdate($this->event); + } +} diff --git a/Tests/EventListener/DoctrineUploaderListenerTest.php b/Tests/EventListener/DoctrineUploaderListenerTest.php deleted file mode 100644 index b1073496..00000000 --- a/Tests/EventListener/DoctrineUploaderListenerTest.php +++ /dev/null @@ -1,289 +0,0 @@ - - */ -class DoctrineUploaderListenerTest extends \PHPUnit_Framework_TestCase -{ - /** - * @var \Vich\UploaderBundle\Adapter\AdapterInterface $adapter - */ - protected $adapter; - - /** - * @var \Vich\UploaderBundle\Metadata\MetadataReader $metadata - */ - protected $metadata; - - /** - * @var \Vich\UploaderBundle\Handler\UploadHandler $handler - */ - protected $handler; - - /** - * @var EventArgs - */ - protected $event; - - /** - * @var DummyEntity - */ - protected $object; - - /** - * @var DoctrineUploaderListener - */ - protected $listener; - - /** - * Sets up the test - */ - public function setUp() - { - $this->adapter = $this->getAdapterMock(); - $this->metadata = $this->getMetadataReaderMock(); - $this->handler = $this->getHandlerMock(); - $this->object = new DummyEntity(); - $this->event = $this->getEventMock(); - - // the adapter is always used to return the object - $this->adapter - ->expects($this->any()) - ->method('getObjectFromEvent') - ->with($this->event) - ->will($this->returnValue($this->object)); - - // in these tests, the adapter is always used with the same object - $this->adapter - ->expects($this->any()) - ->method('getClassName') - ->will($this->returnValue(get_class($this->object))); - - $this->listener = new DoctrineUploaderListener($this->adapter, $this->metadata, $this->handler); - } - - /** - * Test the getSubscribedEvents method. - */ - public function testGetSubscribedEvents() - { - $events = $this->listener->getSubscribedEvents(); - - $this->assertContains('prePersist', $events); - $this->assertContains('preUpdate', $events); - $this->assertContains('postLoad', $events); - $this->assertContains('postRemove', $events); - } - - /** - * Tests the prePersist method. - */ - public function testPrePersist() - { - $this->metadata - ->expects($this->once()) - ->method('isUploadable') - ->with('Vich\UploaderBundle\Tests\DummyEntity') - ->will($this->returnValue(true)); - - $this->handler - ->expects($this->once()) - ->method('handleUpload') - ->with($this->object); - - $this->listener->prePersist($this->event); - } - - /** - * Tests that prePersist skips non-uploadable entity. - */ - public function testPrePersistSkipsNonUploadable() - { - $this->metadata - ->expects($this->once()) - ->method('isUploadable') - ->with('Vich\UploaderBundle\Tests\DummyEntity') - ->will($this->returnValue(false)); - - $this->handler - ->expects($this->never()) - ->method('handleUpload'); - - $this->listener->prePersist($this->event); - } - - /** - * Test the preUpdate method. - */ - public function testPreUpdate() - { - $this->adapter - ->expects($this->once()) - ->method('recomputeChangeSet') - ->with($this->event); - - $this->metadata - ->expects($this->once()) - ->method('isUploadable') - ->with('Vich\UploaderBundle\Tests\DummyEntity') - ->will($this->returnValue(true)); - - $this->handler - ->expects($this->once()) - ->method('handleUpload') - ->with($this->object); - - $this->listener->preUpdate($this->event); - } - - /** - * Test that preUpdate skips non uploadable entity. - */ - public function testPreUpdateSkipsNonUploadable() - { - $this->metadata - ->expects($this->once()) - ->method('isUploadable') - ->with('Vich\UploaderBundle\Tests\DummyEntity') - ->will($this->returnValue(false)); - - $this->adapter - ->expects($this->never()) - ->method('recomputeChangeSet'); - - $this->handler - ->expects($this->never()) - ->method('handleUpload'); - - $this->listener->preUpdate($this->event); - } - - /** - * Test the postLoad method. - */ - public function testPostLoad() - { - $this->metadata - ->expects($this->once()) - ->method('isUploadable') - ->with('Vich\UploaderBundle\Tests\DummyEntity') - ->will($this->returnValue(true)); - - $this->handler - ->expects($this->once()) - ->method('handleHydration') - ->with($this->object); - - $this->listener->postLoad($this->event); - } - - /** - * Test that postLoad skips non uploadable entity. - */ - public function testPostLoadSkipsNonUploadable() - { - $this->metadata - ->expects($this->once()) - ->method('isUploadable') - ->with('Vich\UploaderBundle\Tests\DummyEntity') - ->will($this->returnValue(false)); - - $this->handler - ->expects($this->never()) - ->method('handleHydration'); - - $this->listener->postLoad($this->event); - } - - /** - * Test the postRemove method. - */ - public function testPostRemove() - { - $this->metadata - ->expects($this->once()) - ->method('isUploadable') - ->with('Vich\UploaderBundle\Tests\DummyEntity') - ->will($this->returnValue(true)); - - $this->handler - ->expects($this->once()) - ->method('handleDeletion') - ->with($this->object); - - $this->listener->postRemove($this->event); - } - - /** - * Test that postRemove skips non uploadable entity. - */ - public function testPostRemoveSkipsNonUploadable() - { - $this->metadata - ->expects($this->once()) - ->method('isUploadable') - ->with('Vich\UploaderBundle\Tests\DummyEntity') - ->will($this->returnValue(false)); - - $this->handler - ->expects($this->never()) - ->method('handleDeletion'); - - $this->listener->postRemove($this->event); - } - - /** - * Creates a mock adapter. - * - * @return \Vich\UploaderBundle\Adapter\AdapterInterface The mock adapter. - */ - protected function getAdapterMock() - { - return $this->getMockBuilder('Vich\UploaderBundle\Adapter\AdapterInterface') - ->disableOriginalConstructor() - ->getMock(); - } - - /** - * Creates a mock metadata reader. - * - * @return \Vich\UploaderBundle\Metadata\MetadataReader The mock metadata reader. - */ - protected function getMetadataReaderMock() - { - return $this->getMockBuilder('Vich\UploaderBundle\Metadata\MetadataReader') - ->disableOriginalConstructor() - ->getMock(); - } - - /** - * Creates a mock handler. - * - * @return \Vich\UploaderBundle\Handler\UploadHandler The handler mock. - */ - protected function getHandlerMock() - { - return $this->getMockBuilder('Vich\UploaderBundle\Handler\UploadHandler') - ->disableOriginalConstructor() - ->getMock(); - } - - /** - * Creates a mock doctrine event - * - * @return \Doctrine\Common\EventArgs - */ - protected function getEventMock() - { - return $this->getMockBuilder('Doctrine\Common\EventArgs') - ->disableOriginalConstructor() - ->getMock(); - } -} diff --git a/Tests/EventListener/Propel/CleanListenerTest.php b/Tests/EventListener/Propel/CleanListenerTest.php new file mode 100644 index 00000000..1774b2dc --- /dev/null +++ b/Tests/EventListener/Propel/CleanListenerTest.php @@ -0,0 +1,43 @@ + + */ +class CleanListenerTest extends ListenerTestCase +{ + /** + * Sets up the test + */ + public function setUp() + { + parent::setUp(); + + $this->listener = new CleanListener(self::MAPPING_NAME, $this->adapter, $this->handler); + } + + /** + * Test the getSubscribedEvents method. + */ + public function testGetSubscribedEvents() + { + $events = $this->listener->getSubscribedEvents(); + + $this->assertArrayHasKey('propel.pre_update', $events); + } + + public function testOnUpload() + { + $this->handler + ->expects($this->once()) + ->method('handleCleaning') + ->with($this->object, self::MAPPING_NAME); + + $this->listener->onUpload($this->event); + } +} diff --git a/Tests/EventListener/Propel/InjectListenerTest.php b/Tests/EventListener/Propel/InjectListenerTest.php new file mode 100644 index 00000000..99ec2a03 --- /dev/null +++ b/Tests/EventListener/Propel/InjectListenerTest.php @@ -0,0 +1,43 @@ + + */ +class InjectListenerTest extends ListenerTestCase +{ + /** + * Sets up the test + */ + public function setUp() + { + parent::setUp(); + + $this->listener = new InjectListener(self::MAPPING_NAME, $this->adapter, $this->handler); + } + + /** + * Test the getSubscribedEvents method. + */ + public function testGetSubscribedEvents() + { + $events = $this->listener->getSubscribedEvents(); + + $this->assertArrayHasKey('propel.post_hydrate', $events); + } + + public function testOnHydrate() + { + $this->handler + ->expects($this->once()) + ->method('handleHydration') + ->with($this->object, self::MAPPING_NAME); + + $this->listener->onHydrate($this->event); + } +} diff --git a/Tests/EventListener/Propel/ListenerTestCase.php b/Tests/EventListener/Propel/ListenerTestCase.php new file mode 100644 index 00000000..51c9a8dc --- /dev/null +++ b/Tests/EventListener/Propel/ListenerTestCase.php @@ -0,0 +1,100 @@ + + */ +class ListenerTestCase extends \PHPUnit_Framework_TestCase +{ + const MAPPING_NAME = 'dummy_mapping'; + + /** + * @var \Vich\UploaderBundle\Adapter\AdapterInterface $adapter + */ + protected $adapter; + + /** + * @var \Vich\UploaderBundle\Handler\UploadHandler $handler + */ + protected $handler; + + /** + * @var PropelUploaderListener $listener + */ + protected $listener; + + /** + * @var EventArgs + */ + protected $event; + + /** + * @var DummyEntity + */ + protected $object; + + /** + * Sets up the test + */ + public function setUp() + { + $this->adapter = $this->getAdapterMock(); + $this->handler = $this->getHandlerMock(); + $this->object = new DummyEntity(); + $this->event = $this->getEventMock(); + + // the adapter is always used to return the object + $this->adapter + ->expects($this->any()) + ->method('getObjectFromEvent') + ->with($this->event) + ->will($this->returnValue($this->object)); + + // in these tests, the adapter is always used with the same object + $this->adapter + ->expects($this->any()) + ->method('getClassName') + ->will($this->returnValue(get_class($this->object))); + } + + /** + * Creates a mock adapter. + * + * @return \Vich\UploaderBundle\Adapter\AdapterInterface The mock adapter. + */ + protected function getAdapterMock() + { + return $this->getMockBuilder('Vich\UploaderBundle\Adapter\AdapterInterface') + ->disableOriginalConstructor() + ->getMock(); + } + + /** + * Creates a mock handler. + * + * @return \Vich\UploaderBundle\Handler\UploadHandler The handler mock. + */ + protected function getHandlerMock() + { + return $this->getMockBuilder('Vich\UploaderBundle\Handler\UploadHandler') + ->disableOriginalConstructor() + ->getMock(); + } + + /** + * Creates a mock event. + * + * @return \Symfony\Component\EventDispatcher\GenericEvent The mock event. + */ + protected function getEventMock() + { + return $this->getMockBuilder('\Symfony\Component\EventDispatcher\GenericEvent') + ->disableOriginalConstructor() + ->getMock(); + } +} diff --git a/Tests/EventListener/Propel/RemoveListenerTest.php b/Tests/EventListener/Propel/RemoveListenerTest.php new file mode 100644 index 00000000..9bc26279 --- /dev/null +++ b/Tests/EventListener/Propel/RemoveListenerTest.php @@ -0,0 +1,43 @@ + + */ +class RemoveListenerTest extends ListenerTestCase +{ + /** + * Sets up the test + */ + public function setUp() + { + parent::setUp(); + + $this->listener = new RemoveListener(self::MAPPING_NAME, $this->adapter, $this->handler); + } + + /** + * Test the getSubscribedEvents method. + */ + public function testGetSubscribedEvents() + { + $events = $this->listener->getSubscribedEvents(); + + $this->assertArrayHasKey('propel.post_delete', $events); + } + + public function testOnDelete() + { + $this->handler + ->expects($this->once()) + ->method('handleDeletion') + ->with($this->object, self::MAPPING_NAME); + + $this->listener->onDelete($this->event); + } +} diff --git a/Tests/EventListener/Propel/UploadListenerTest.php b/Tests/EventListener/Propel/UploadListenerTest.php new file mode 100644 index 00000000..d1a4595d --- /dev/null +++ b/Tests/EventListener/Propel/UploadListenerTest.php @@ -0,0 +1,44 @@ + + */ +class UploadListenerTest extends ListenerTestCase +{ + /** + * Sets up the test + */ + public function setUp() + { + parent::setUp(); + + $this->listener = new UploadListener(self::MAPPING_NAME, $this->adapter, $this->handler); + } + + /** + * Test the getSubscribedEvents method. + */ + public function testGetSubscribedEvents() + { + $events = $this->listener->getSubscribedEvents(); + + $this->assertArrayHasKey('propel.pre_update', $events); + $this->assertArrayHasKey('propel.pre_insert', $events); + } + + public function testOnUpload() + { + $this->handler + ->expects($this->once()) + ->method('handleUpload') + ->with($this->object, self::MAPPING_NAME); + + $this->listener->onUpload($this->event); + } +} diff --git a/Tests/EventListener/PropelUploaderListenerTest.php b/Tests/EventListener/PropelUploaderListenerTest.php deleted file mode 100644 index f92e5f8c..00000000 --- a/Tests/EventListener/PropelUploaderListenerTest.php +++ /dev/null @@ -1,142 +0,0 @@ - - */ -class PropelUploaderListenerTest extends \PHPUnit_Framework_TestCase -{ - /** - * @var \Vich\UploaderBundle\Adapter\AdapterInterface $adapter - */ - protected $adapter; - - /** - * @var \Vich\UploaderBundle\Handler\UploadHandler $handler - */ - protected $handler; - - /** - * @var PropelUploaderListener $listener - */ - protected $listener; - - /** - * Sets up the test - */ - public function setUp() - { - $this->adapter = $this->getAdapterMock(); - $this->handler = $this->getHandlerMock(); - $this->listener = new PropelUploaderListener($this->adapter, $this->handler); - } - - /** - * Test the getSubscribedEvents method. - */ - public function testGetSubscribedEvents() - { - $events = $this->listener->getSubscribedEvents(); - - $this->assertArrayHasKey('propel.pre_insert', $events); - $this->assertArrayHasKey('propel.pre_update', $events); - $this->assertArrayHasKey('propel.post_delete', $events); - $this->assertArrayHasKey('propel.post_hydrate', $events); - } - - public function testOnUpload() - { - $obj = new DummyEntity(); - $event = $this->getEventMock(); - - $this->adapter - ->expects($this->once()) - ->method('getObjectFromEvent') - ->will($this->returnValue($obj)); - - $this->handler - ->expects($this->once()) - ->method('handleUpload') - ->with($obj); - - $this->listener->onUpload($event); - } - - public function testOnConstruct() - { - $obj = new DummyEntity(); - $event = $this->getEventMock(); - - $this->adapter - ->expects($this->once()) - ->method('getObjectFromEvent') - ->will($this->returnValue($obj)); - - $this->handler - ->expects($this->once()) - ->method('handleHydration') - ->with($obj); - - $this->listener->onHydrate($event); - } - - public function testOnDelete() - { - $obj = new DummyEntity(); - $event = $this->getEventMock(); - - $this->adapter - ->expects($this->once()) - ->method('getObjectFromEvent') - ->will($this->returnValue($obj)); - - $this->handler - ->expects($this->once()) - ->method('handleDeletion') - ->with($obj); - - $this->listener->onDelete($event); - } - - /** - * Creates a mock adapter. - * - * @return \Vich\UploaderBundle\Adapter\AdapterInterface The mock adapter. - */ - protected function getAdapterMock() - { - return $this->getMockBuilder('Vich\UploaderBundle\Adapter\AdapterInterface') - ->disableOriginalConstructor() - ->getMock(); - } - - /** - * Creates a mock handler. - * - * @return \Vich\UploaderBundle\Handler\UploadHandler The handler mock. - */ - protected function getHandlerMock() - { - return $this->getMockBuilder('Vich\UploaderBundle\Handler\UploadHandler') - ->disableOriginalConstructor() - ->getMock(); - } - - /** - * Creates a mock event. - * - * @return \Symfony\Component\EventDispatcher\GenericEvent The mock event. - */ - protected function getEventMock() - { - return $this->getMockBuilder('\Symfony\Component\EventDispatcher\GenericEvent') - ->disableOriginalConstructor() - ->getMock(); - } -} From ff066a1dfa4086eb9353db2c23ddd991e051f944 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Wed, 25 Dec 2013 15:38:21 +0000 Subject: [PATCH 44/54] Removed useless else statements --- Adapter/ODM/MongoDB/MongoDBAdapter.php | 4 ++-- Adapter/ORM/DoctrineORMAdapter.php | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Adapter/ODM/MongoDB/MongoDBAdapter.php b/Adapter/ODM/MongoDB/MongoDBAdapter.php index 12e4a61e..d33691df 100644 --- a/Adapter/ODM/MongoDB/MongoDBAdapter.php +++ b/Adapter/ODM/MongoDB/MongoDBAdapter.php @@ -40,8 +40,8 @@ public function getClassName($object) { if ($object instanceof Proxy) { return get_parent_class($object); - } else { - return get_class($object); } + + return get_class($object); } } diff --git a/Adapter/ORM/DoctrineORMAdapter.php b/Adapter/ORM/DoctrineORMAdapter.php index 024124c1..74ee8020 100644 --- a/Adapter/ORM/DoctrineORMAdapter.php +++ b/Adapter/ORM/DoctrineORMAdapter.php @@ -40,8 +40,8 @@ public function getClassName($object) { if ($object instanceof Proxy) { return get_parent_class($object); - } else { - return get_class($object); } + + return get_class($object); } } From 8ae1a5d52a9bb68be7017636e7faf479067b3ba1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Wed, 25 Dec 2013 15:48:06 +0000 Subject: [PATCH 45/54] Renamed drivers --- .../{Annotation.php => AnnotationDriver.php} | 2 +- Metadata/Driver/{Chain.php => ChainDriver.php} | 2 +- Metadata/Driver/{Xml.php => XmlDriver.php} | 5 ++++- Metadata/Driver/{Yaml.php => YamlDriver.php} | 2 +- Resources/config/mapping.xml | 8 ++++---- ...AnnotationTest.php => AnnotationDriverTest.php} | 14 +++++++------- .../Driver/{YamlTest.php => YamlDriverTest.php} | 10 +++++----- 7 files changed, 23 insertions(+), 20 deletions(-) rename Metadata/Driver/{Annotation.php => AnnotationDriver.php} (97%) rename Metadata/Driver/{Chain.php => ChainDriver.php} (95%) rename Metadata/Driver/{Xml.php => XmlDriver.php} (95%) rename Metadata/Driver/{Yaml.php => YamlDriver.php} (97%) rename Tests/Metadata/Driver/{AnnotationTest.php => AnnotationDriverTest.php} (91%) rename Tests/Metadata/Driver/{YamlTest.php => YamlDriverTest.php} (93%) diff --git a/Metadata/Driver/Annotation.php b/Metadata/Driver/AnnotationDriver.php similarity index 97% rename from Metadata/Driver/Annotation.php rename to Metadata/Driver/AnnotationDriver.php index 4ab2a7f1..56119bab 100644 --- a/Metadata/Driver/Annotation.php +++ b/Metadata/Driver/AnnotationDriver.php @@ -12,7 +12,7 @@ * * @author Kévin Gomez */ -class Annotation implements DriverInterface +class AnnotationDriver implements DriverInterface { const UPLOADABLE_ANNOTATION = 'Vich\UploaderBundle\Mapping\Annotation\Uploadable'; const UPLOADABLE_FIELD_ANNOTATION = 'Vich\UploaderBundle\Mapping\Annotation\UploadableField'; diff --git a/Metadata/Driver/Chain.php b/Metadata/Driver/ChainDriver.php similarity index 95% rename from Metadata/Driver/Chain.php rename to Metadata/Driver/ChainDriver.php index d347fcd3..f4c29a49 100644 --- a/Metadata/Driver/Chain.php +++ b/Metadata/Driver/ChainDriver.php @@ -4,7 +4,7 @@ use Metadata\Driver\AdvancedDriverInterface; -class Chain implements AdvancedDriverInterface +class ChainDriver implements AdvancedDriverInterface { private $drivers; diff --git a/Metadata/Driver/Xml.php b/Metadata/Driver/XmlDriver.php similarity index 95% rename from Metadata/Driver/Xml.php rename to Metadata/Driver/XmlDriver.php index 37d38e25..d62a871c 100644 --- a/Metadata/Driver/Xml.php +++ b/Metadata/Driver/XmlDriver.php @@ -9,8 +9,11 @@ * * @author Kévin Gomez */ -class Xml extends AbstractFileDriver +class XmlDriver extends AbstractFileDriver { + /** + * {@inheritDoc} + */ protected function loadMetadataFromFile($file, \ReflectionClass $class = null) { $previous = libxml_use_internal_errors(true); diff --git a/Metadata/Driver/Yaml.php b/Metadata/Driver/YamlDriver.php similarity index 97% rename from Metadata/Driver/Yaml.php rename to Metadata/Driver/YamlDriver.php index 616e95c1..affa3165 100644 --- a/Metadata/Driver/Yaml.php +++ b/Metadata/Driver/YamlDriver.php @@ -11,7 +11,7 @@ * * @author Kévin Gomez */ -class Yaml extends AbstractFileDriver +class YamlDriver extends AbstractFileDriver { /** * {@inheritDoc} diff --git a/Resources/config/mapping.xml b/Resources/config/mapping.xml index 0ff14c3f..daa7c32a 100644 --- a/Resources/config/mapping.xml +++ b/Resources/config/mapping.xml @@ -12,19 +12,19 @@ - + - + - + - + diff --git a/Tests/Metadata/Driver/AnnotationTest.php b/Tests/Metadata/Driver/AnnotationDriverTest.php similarity index 91% rename from Tests/Metadata/Driver/AnnotationTest.php rename to Tests/Metadata/Driver/AnnotationDriverTest.php index 53d31994..dbbda8f6 100644 --- a/Tests/Metadata/Driver/AnnotationTest.php +++ b/Tests/Metadata/Driver/AnnotationDriverTest.php @@ -3,16 +3,16 @@ namespace Vich\UploaderBundle\Tests\Metadata\Driver; use Vich\UploaderBundle\Mapping\Annotation\UploadableField; -use Vich\UploaderBundle\Metadata\Driver\Annotation; +use Vich\UploaderBundle\Metadata\Driver\AnnotationDriver; use Vich\UploaderBundle\Tests\DummyEntity; use Vich\UploaderBundle\Tests\TwoFieldsDummyEntity; /** - * AnnotationTest + * AnnotationDriverTest * * @author Kévin Gomez */ -class AnnotationTest extends \PHPUnit_Framework_TestCase +class AnnotationDriverTest extends \PHPUnit_Framework_TestCase { public function testReadUploadableAnnotation() { @@ -31,7 +31,7 @@ public function testReadUploadableAnnotation() 'fileNameProperty' => 'fileName' )))); - $driver = new Annotation($reader); + $driver = new AnnotationDriver($reader); $metadata = $driver->loadMetadataForClass(new \ReflectionClass($entity)); $this->assertInstanceOf('\Vich\UploaderBundle\Metadata\ClassMetadata', $metadata); @@ -58,7 +58,7 @@ public function testReadUploadableAnnotationReturnsNullWhenNonePresent() ->expects($this->never()) ->method('getPropertyAnnotation'); - $driver = new Annotation($reader); + $driver = new AnnotationDriver($reader); $metadata = $driver->loadMetadataForClass(new \ReflectionClass($entity)); $this->assertNull($metadata); @@ -88,7 +88,7 @@ public function testReadTwoUploadableFields() 'fileNameProperty' => 'imageName' )))); - $driver = new Annotation($reader); + $driver = new AnnotationDriver($reader); $metadata = $driver->loadMetadataForClass(new \ReflectionClass($entity)); $this->assertEquals(array( @@ -115,7 +115,7 @@ public function testReadNoUploadableFieldsWhenNoneExist() ->method('getClassAnnotation') ->will($this->returnValue('something not null')); - $driver = new Annotation($reader); + $driver = new AnnotationDriver($reader); $metadata = $driver->loadMetadataForClass(new \ReflectionClass($entity)); $this->assertEmpty($metadata->fields); diff --git a/Tests/Metadata/Driver/YamlTest.php b/Tests/Metadata/Driver/YamlDriverTest.php similarity index 93% rename from Tests/Metadata/Driver/YamlTest.php rename to Tests/Metadata/Driver/YamlDriverTest.php index 0986506c..a8e45a56 100644 --- a/Tests/Metadata/Driver/YamlTest.php +++ b/Tests/Metadata/Driver/YamlDriverTest.php @@ -3,14 +3,14 @@ namespace Vich\UploaderBundle\Tests\Metadata\Driver; use Doctrine\ORM\Mapping\ClassMetadata; -use Vich\UploaderBundle\Metadata\Driver\Yaml; +use Vich\UploaderBundle\Metadata\Driver\YamlDriver; /** - * YamlTest + * YamlDriverTest * * @author Kévin Gomez */ -class YamlTest extends \PHPUnit_Framework_TestCase +class YamlDriverTest extends \PHPUnit_Framework_TestCase { /** * @expectedException RuntimeException @@ -47,7 +47,7 @@ public function testLoadMetadataForClass($mapping, $expectedMetadata) protected function getDriver(\ReflectionClass $class, $found = true) { $fileLocator = $this->getMock('\Metadata\Driver\FileLocatorInterface'); - $driver = new TestableYaml($fileLocator); + $driver = new TestableYamlDriver($fileLocator); $fileLocator ->expects($this->once()) @@ -109,7 +109,7 @@ public function fieldsProvider() } } -class TestableYaml extends Yaml +class TestableYamlDriver extends YamlDriver { public $mappingContent; From 030c79473ce0d8b1a6a2d7e315b5376cfd94c222 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Wed, 25 Dec 2013 15:50:50 +0000 Subject: [PATCH 46/54] Added missing check in PropertyMappingFactory --- Mapping/PropertyMappingFactory.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Mapping/PropertyMappingFactory.php b/Mapping/PropertyMappingFactory.php index f289ec98..457ffc71 100644 --- a/Mapping/PropertyMappingFactory.php +++ b/Mapping/PropertyMappingFactory.php @@ -161,7 +161,7 @@ protected function createMapping($obj, $fieldName, array $mappingData) $config = $this->mappings[$mappingData['mapping']]; - $mapping = new PropertyMapping($mappingData['propertyName'] ?: $fieldName, $mappingData['fileNameProperty']); + $mapping = new PropertyMapping(isset($mappingData['propertyName']) ? $mappingData['propertyName'] : $fieldName, $mappingData['fileNameProperty']); $mapping->setMappingName($mappingData['mapping']); $mapping->setMapping($config); From 6d2ce009879ffb724477cdce72062889dc2aece7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Wed, 25 Dec 2013 17:40:23 +0100 Subject: [PATCH 47/54] Fixed propel compiler pass --- .../CompilerPass/RegisterPropelModelsPass.php | 17 ++++++++++++----- DependencyInjection/VichUploaderExtension.php | 7 +++++-- 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/DependencyInjection/CompilerPass/RegisterPropelModelsPass.php b/DependencyInjection/CompilerPass/RegisterPropelModelsPass.php index 57b4eca6..80442650 100644 --- a/DependencyInjection/CompilerPass/RegisterPropelModelsPass.php +++ b/DependencyInjection/CompilerPass/RegisterPropelModelsPass.php @@ -21,12 +21,19 @@ public function process(ContainerBuilder $container) return; } - $propelListener = $container->getDefinition('vich_uploader.listener.uploader.propel'); $metadata = $container->get('vich_uploader.metadata_reader'); - foreach ($metadata->getUploadableClasses() as $class) { - $propelListener->addTag('propel.event_subscriber', array( - 'class' => $class - )); + $classes = $metadata->getUploadableClasses(); + + foreach ($container->findTaggedServiceIds('vich_uploader.listener') as $id => $attributes) { + $listener = $container->getDefinition($id); + $listener->setClass($container->getDefinition($listener->getParent())->getClass()); + $listener->setPublic(true); + + foreach ($classes as $class) { + $listener->addTag('propel.event_subscriber', array( + 'class' => $class + )); + } } } } diff --git a/DependencyInjection/VichUploaderExtension.php b/DependencyInjection/VichUploaderExtension.php index d434513c..be40da0f 100644 --- a/DependencyInjection/VichUploaderExtension.php +++ b/DependencyInjection/VichUploaderExtension.php @@ -93,7 +93,8 @@ protected function registerEventListeners(ContainerBuilder $container, array $co $definition = $container ->setDefinition(sprintf('vich_uploader.listener.%s.%s', $service, $name), new DefinitionDecorator(sprintf('vich_uploader.listener.%s.%s', $service, $driver))) - ->replaceArgument(0, $name); + ->replaceArgument(0, $name) + ->addTag('vich_uploader.listener'); if (isset($this->tagMap[$driver])) { $definition->addTag($this->tagMap[$driver]); @@ -102,7 +103,9 @@ protected function registerEventListeners(ContainerBuilder $container, array $co $definition = $container ->setDefinition(sprintf('vich_uploader.listener.upload.%s', $name), new DefinitionDecorator(sprintf('vich_uploader.listener.upload.%s', $driver))) - ->replaceArgument(0, $name); + ->replaceArgument(0, $name) + ->addTag('vich_uploader.listener'); + if (isset($this->tagMap[$driver])) { $definition->addTag($this->tagMap[$driver], array('priority' => -50)); } From 8500f0e4ab2621c13217bc833bebf62cdf67537a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Wed, 25 Dec 2013 18:42:54 +0100 Subject: [PATCH 48/54] Added tests for the UploadHandler --- Handler/UploadHandler.php | 7 +- Tests/Handler/UploadHandlerTest.php | 412 ++++++++++++++++++++++++++++ Tests/Injector/FileInjectorTest.php | 2 +- 3 files changed, 419 insertions(+), 2 deletions(-) create mode 100644 Tests/Handler/UploadHandlerTest.php diff --git a/Handler/UploadHandler.php b/Handler/UploadHandler.php index 95466914..8feb7b83 100644 --- a/Handler/UploadHandler.php +++ b/Handler/UploadHandler.php @@ -54,6 +54,11 @@ public function handleUpload($object, $mapping) } $mapping = $this->factory->fromName($object, $mapping); + $file = $mapping->getFile($object); + + if ($file === null || !($file instanceof UploadedFile)) { + return; + } $this->storage->upload($object, $mapping); $this->injector->injectFiles($object, $mapping); @@ -91,7 +96,7 @@ public function handleHydration($object, $mapping) $this->injector->injectFiles($object, $mapping); } - public function handleDeletion($obj, $mapping) + public function handleDeletion($object, $mapping) { if (!$this->factory->hasMapping($object, $mapping)) { return; diff --git a/Tests/Handler/UploadHandlerTest.php b/Tests/Handler/UploadHandlerTest.php new file mode 100644 index 00000000..f864d3ed --- /dev/null +++ b/Tests/Handler/UploadHandlerTest.php @@ -0,0 +1,412 @@ + + */ +class UploadHandlerTest extends \PHPUnit_Framework_TestCase +{ + /** + * @var FileInjectorInterface + */ + protected $injector; + + /** + * @var PropertyMappingFactory + */ + protected $factory; + + /** + * @var UploadHandler + */ + protected $storage; + + /** + * @var UploadHandler + */ + protected $handler; + + /** + * @var DummyEntity + */ + protected $object; + + /** + * Sets up the test + */ + public function setUp() + { + $this->factory = $this->getPropertyMappingFactoryMock(); + $this->injector = $this->getFileInjectorMock(); + $this->storage = $this->getStorageMock(); + $this->object = new DummyEntity(); + + $this->handler = new UploadHandler($this->factory, $this->storage, $this->injector); + } + + public function testHandleUploadDoesNothingIfMappingDoesntExistForObject() + { + $this->factory + ->expects($this->once()) + ->method('hasMapping') + ->with($this->object, 'dummy_mapping') + ->will($this->returnValue(false)); + + $this->storage + ->expects($this->never()) + ->method('upload'); + + $this->injector + ->expects($this->never()) + ->method('injectFiles'); + + $this->handler->handleUpload($this->object, 'dummy_mapping'); + } + + /** + * @dataProvider invalidUploadedFileProvider + */ + public function testHandleUploadDoesNothingIfNoFileIsUploaded($file) + { + $mapping = $this->getPropertyMappingMock(); + + $this->factory + ->expects($this->once()) + ->method('hasMapping') + ->with($this->object, 'dummy_mapping') + ->will($this->returnValue(true)); + + $this->factory + ->expects($this->once()) + ->method('fromName') + ->with($this->object, 'dummy_mapping') + ->will($this->returnValue($mapping)); + + $mapping + ->expects($this->once()) + ->method('getFile') + ->with($this->object) + ->will($this->returnValue($file)); + + $this->storage + ->expects($this->never()) + ->method('upload'); + + $this->injector + ->expects($this->never()) + ->method('injectFiles'); + + $this->handler->handleUpload($this->object, 'dummy_mapping'); + } + + public function testHandleUpload() + { + $file = $this->getMockBuilder('Symfony\Component\HttpFoundation\File\UploadedFile') + ->disableOriginalConstructor() + ->getMock(); + + $mapping = $this->getPropertyMappingMock(); + + $this->factory + ->expects($this->once()) + ->method('hasMapping') + ->with($this->object, 'dummy_mapping') + ->will($this->returnValue(true)); + + $this->factory + ->expects($this->once()) + ->method('fromName') + ->with($this->object, 'dummy_mapping') + ->will($this->returnValue($mapping)); + + $mapping + ->expects($this->once()) + ->method('getFile') + ->with($this->object) + ->will($this->returnValue($file)); + + $this->storage + ->expects($this->once()) + ->method('upload') + ->with($this->object, $mapping); + + $this->injector + ->expects($this->once()) + ->method('injectFiles') + ->with($this->object, $mapping); + + $this->handler->handleUpload($this->object, 'dummy_mapping'); + } + + public function testHandleCleaningDoesNothingIfMappingDoesntExistForObject() + { + $this->factory + ->expects($this->once()) + ->method('hasMapping') + ->with($this->object, 'dummy_mapping') + ->will($this->returnValue(false)); + + $this->storage + ->expects($this->never()) + ->method('remove'); + + $this->handler->handleCleaning($this->object, 'dummy_mapping'); + } + + public function testHandleCleaningDoesNothingIfNoOldFileIsPresent() + { + $file = $this->getMockBuilder('Symfony\Component\HttpFoundation\File\UploadedFile') + ->disableOriginalConstructor() + ->getMock(); + + $mapping = $this->getPropertyMappingMock(); + + $this->factory + ->expects($this->once()) + ->method('hasMapping') + ->with($this->object, 'dummy_mapping') + ->will($this->returnValue(true)); + + $this->factory + ->expects($this->once()) + ->method('fromName') + ->with($this->object, 'dummy_mapping') + ->will($this->returnValue($mapping)); + + $mapping + ->expects($this->once()) + ->method('getFile') + ->with($this->object) + ->will($this->returnValue($file)); + $mapping + ->expects($this->once()) + ->method('getFileName') + ->with($this->object) + ->will($this->returnValue(null)); + + $this->storage + ->expects($this->never()) + ->method('remove'); + + $this->handler->handleCleaning($this->object, 'dummy_mapping'); + } + + /** + * @dataProvider invalidUploadedFileProvider + */ + public function testHandleCleaningDoesNothingIfNoFileIsUploaded($file) + { + $mapping = $this->getPropertyMappingMock(); + + $this->factory + ->expects($this->once()) + ->method('hasMapping') + ->with($this->object, 'dummy_mapping') + ->will($this->returnValue(true)); + + $this->factory + ->expects($this->once()) + ->method('fromName') + ->with($this->object, 'dummy_mapping') + ->will($this->returnValue($mapping)); + + $mapping + ->expects($this->once()) + ->method('getFile') + ->with($this->object) + ->will($this->returnValue($file)); + + $this->storage + ->expects($this->never()) + ->method('remove'); + + $this->handler->handleCleaning($this->object, 'dummy_mapping'); + } + + public function invalidUploadedFileProvider() + { + $file = $this->getMockBuilder('Symfony\Component\HttpFoundation\File\File') + ->disableOriginalConstructor() + ->getMock(); + + return array( + array(null), + array('lala'), + array(new \DateTime()), + array($file), + ); + } + + public function testHandleCleaning() + { + $file = $this->getMockBuilder('Symfony\Component\HttpFoundation\File\UploadedFile') + ->disableOriginalConstructor() + ->getMock(); + + $mapping = $this->getPropertyMappingMock(); + + $this->factory + ->expects($this->once()) + ->method('hasMapping') + ->with($this->object, 'dummy_mapping') + ->will($this->returnValue(true)); + + $this->factory + ->expects($this->once()) + ->method('fromName') + ->with($this->object, 'dummy_mapping') + ->will($this->returnValue($mapping)); + + $mapping + ->expects($this->once()) + ->method('getFile') + ->with($this->object) + ->will($this->returnValue($file)); + $mapping + ->expects($this->once()) + ->method('getFileName') + ->with($this->object) + ->will($this->returnValue('foo.txt')); + + $this->storage + ->expects($this->once()) + ->method('remove') + ->with($this->object, $mapping); + + $this->handler->handleCleaning($this->object, 'dummy_mapping'); + } + + public function testHandleHydrationDoesNothingIfMappingDoesntExistForObject() + { + $this->factory + ->expects($this->once()) + ->method('hasMapping') + ->with($this->object, 'dummy_mapping') + ->will($this->returnValue(false)); + + $this->injector + ->expects($this->never()) + ->method('injectFiles'); + + $this->handler->handleHydration($this->object, 'dummy_mapping'); + } + + public function testHandleHydration() + { + $mapping = $this->getPropertyMappingMock(); + + $this->factory + ->expects($this->once()) + ->method('hasMapping') + ->with($this->object, 'dummy_mapping') + ->will($this->returnValue(true)); + + $this->factory + ->expects($this->once()) + ->method('fromName') + ->with($this->object, 'dummy_mapping') + ->will($this->returnValue($mapping)); + + $this->injector + ->expects($this->once()) + ->method('injectFiles') + ->with($this->object, $mapping); + + $this->handler->handleHydration($this->object, 'dummy_mapping'); + } + + public function testHandleDeletionDoesNothingIfMappingDoesntExistForObject() + { + $this->factory + ->expects($this->once()) + ->method('hasMapping') + ->with($this->object, 'dummy_mapping') + ->will($this->returnValue(false)); + + $this->injector + ->expects($this->never()) + ->method('remove'); + + $this->handler->handleDeletion($this->object, 'dummy_mapping'); + } + + public function testHandleDeletion() + { + $mapping = $this->getPropertyMappingMock(); + + $this->factory + ->expects($this->once()) + ->method('hasMapping') + ->with($this->object, 'dummy_mapping') + ->will($this->returnValue(true)); + + $this->factory + ->expects($this->once()) + ->method('fromName') + ->with($this->object, 'dummy_mapping') + ->will($this->returnValue($mapping)); + + $this->storage + ->expects($this->once()) + ->method('remove') + ->with($this->object, $mapping); + + $this->handler->handleDeletion($this->object, 'dummy_mapping'); + } + + /** + * Creates a mock property mapping factory + * + * @return \Vich\UploaderBundle\Mapping\PropertyMappingFactory + */ + protected function getPropertyMappingFactoryMock() + { + return $this->getMockBuilder('Vich\UploaderBundle\Mapping\PropertyMappingFactory') + ->disableOriginalConstructor() + ->getMock(); + } + + /** + * Gets a mock storage. + * + * @return \Vich\UploaderBundle\Storage\StorageInterface + */ + protected function getStorageMock() + { + return $this->getMockBuilder('Vich\UploaderBundle\Storage\StorageInterface') + ->disableOriginalConstructor() + ->getMock(); + } + + /** + * Gets a mock file injector. + * + * @return \Vich\UploaderBundle\Injector\FileInjectorInterface + */ + protected function getFileInjectorMock() + { + return $this->getMockBuilder('Vich\UploaderBundle\Injector\FileInjectorInterface') + ->disableOriginalConstructor() + ->getMock(); + } + + /** + * Gets a mock property mapping. + * + * @return \Vich\UploaderBundle\Mapping\PropertyMapping + */ + protected function getPropertyMappingMock() + { + return $this->getMockBuilder('Vich\UploaderBundle\Mapping\PropertyMapping') + ->disableOriginalConstructor() + ->getMock(); + } +} diff --git a/Tests/Injector/FileInjectorTest.php b/Tests/Injector/FileInjectorTest.php index e09d4c99..284dd4f7 100644 --- a/Tests/Injector/FileInjectorTest.php +++ b/Tests/Injector/FileInjectorTest.php @@ -101,7 +101,7 @@ public function testPropertyIsNullWhenFileNamePropertyIsNull() * * @return \Vich\UploaderBundle\Mapping\PropertyMapping The property. */ - protected function getPropertyMappingMock($injectOnLoadEnabled = true) + protected function getPropertyMappingMock() { return $this->getMockBuilder('Vich\UploaderBundle\Mapping\PropertyMapping') ->disableOriginalConstructor() From fa652ef35c2c5fb74130d7d87234956413e0ee11 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Wed, 25 Dec 2013 18:46:48 +0100 Subject: [PATCH 49/54] Cleaned a bit adapters tests --- Tests/Adapter/ORM/DoctrineORMAdapterTest.php | 55 +++++++++----------- Tests/Adapter/Propel/PropelAdapterTest.php | 23 +++++--- 2 files changed, 42 insertions(+), 36 deletions(-) diff --git a/Tests/Adapter/ORM/DoctrineORMAdapterTest.php b/Tests/Adapter/ORM/DoctrineORMAdapterTest.php index a3d807d8..271ca787 100644 --- a/Tests/Adapter/ORM/DoctrineORMAdapterTest.php +++ b/Tests/Adapter/ORM/DoctrineORMAdapterTest.php @@ -13,28 +13,31 @@ */ class DoctrineORMAdapterTest extends \PHPUnit_Framework_TestCase { + public static function setUpBeforeClass() + { + if (!class_exists('Doctrine\ORM\Event\LifecycleEventArgs')) { + self::markTestSkipped('Doctrine\ORM\Event\LifecycleEventArgs does not exist.'); + } + } + /** * Test the getObjectFromEvent method. */ public function testGetObjectFromEvent() { - if (!class_exists('Doctrine\ORM\Event\LifecycleEventArgs')) { - $this->markTestSkipped('Doctrine\ORM\Event\LifecycleEventArgs does not exist.'); - } else { - $entity = $this->getMock('Vich\UploaderBundle\Tests\DummyEntity'); + $entity = $this->getMock('Vich\UploaderBundle\Tests\DummyEntity'); - $args = $this->getMockBuilder('Doctrine\ORM\Event\LifecycleEventArgs') - ->disableOriginalConstructor() - ->getMock(); - $args - ->expects($this->once()) - ->method('getEntity') - ->will($this->returnValue($entity)); + $args = $this->getMockBuilder('Doctrine\ORM\Event\LifecycleEventArgs') + ->disableOriginalConstructor() + ->getMock(); + $args + ->expects($this->once()) + ->method('getEntity') + ->will($this->returnValue($entity)); - $adapter = new DoctrineORMAdapter(); + $adapter = new DoctrineORMAdapter(); - $this->assertEquals($entity, $adapter->getObjectFromEvent($args)); - } + $this->assertEquals($entity, $adapter->getObjectFromEvent($args)); } /** @@ -42,15 +45,11 @@ public function testGetObjectFromEvent() */ public function testGetClassName() { - if (!interface_exists('Doctrine\ORM\Proxy\Proxy')) { - $this->markTestSkipped('Doctrine\ORM\Proxy\Proxy does not exist.'); - } else { - $obj = new DummyEntity(); - $adapter = new DoctrineORMAdapter(); - $class = $adapter->getClassName($obj); + $obj = new DummyEntity(); + $adapter = new DoctrineORMAdapter(); + $class = $adapter->getClassName($obj); - $this->assertEquals('Vich\UploaderBundle\Tests\DummyEntity', $class); - } + $this->assertEquals('Vich\UploaderBundle\Tests\DummyEntity', $class); } /** @@ -58,14 +57,10 @@ public function testGetClassName() */ public function testGetClassNameWithProxy() { - if (!interface_exists('Doctrine\ORM\Proxy\Proxy')) { - $this->markTestSkipped('Doctrine\ORM\Proxy\Proxy does not exist.'); - } else { - $obj = new DummyEntityProxyORM(); - $adapter = new DoctrineORMAdapter(); - $class = $adapter->getClassName($obj); + $obj = new DummyEntityProxyORM(); + $adapter = new DoctrineORMAdapter(); + $class = $adapter->getClassName($obj); - $this->assertEquals('Vich\UploaderBundle\Tests\DummyEntity', $class); - } + $this->assertEquals('Vich\UploaderBundle\Tests\DummyEntity', $class); } } diff --git a/Tests/Adapter/Propel/PropelAdapterTest.php b/Tests/Adapter/Propel/PropelAdapterTest.php index 5987e71f..1a7b5623 100644 --- a/Tests/Adapter/Propel/PropelAdapterTest.php +++ b/Tests/Adapter/Propel/PropelAdapterTest.php @@ -11,6 +11,13 @@ */ class PropelAdapterTest extends \PHPUnit_Framework_TestCase { + protected $adapter; + + public function setUp() + { + $this->adapter = new PropelAdapter(); + } + public function testGetObjectFromEvent() { $event = $this->getMock('\Symfony\Component\EventDispatcher\GenericEvent'); @@ -19,17 +26,21 @@ public function testGetObjectFromEvent() ->method('getSubject') ->will($this->returnValue(42)); - $adapter = new PropelAdapter(); - $this->assertSame(42, $adapter->getObjectFromEvent($event)); + $this->assertSame(42, $this->adapter->getObjectFromEvent($event)); } public function testGetClassName() { - $adapter = new PropelAdapter(); - $obj = new \DateTime(); - $class = $adapter->getClassName($obj); - $this->assertSame('DateTime', $class); + $this->assertSame('DateTime', $this->adapter->getClassName($obj)); + } + + public function testRecomputeChangeset() + { + $event = $this->getMock('\Symfony\Component\EventDispatcher\GenericEvent'); + + // does nothing but should be callable + $this->adapter->recomputeChangeSet($event); } } From 400fd9e11e6a2f299b6d19b15f05ca9cfcf24783 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Wed, 25 Dec 2013 18:57:26 +0100 Subject: [PATCH 50/54] Renamed UploadHandler methods --- EventListener/Doctrine/CleanListener.php | 2 +- EventListener/Doctrine/InjectListener.php | 2 +- EventListener/Doctrine/RemoveListener.php | 2 +- EventListener/Doctrine/UploadListener.php | 4 +- EventListener/Propel/CleanListener.php | 2 +- EventListener/Propel/InjectListener.php | 2 +- EventListener/Propel/RemoveListener.php | 2 +- EventListener/Propel/UploadListener.php | 2 +- Handler/UploadHandler.php | 8 ++-- .../Doctrine/CleanListenerTest.php | 4 +- .../Doctrine/InjectListenerTest.php | 4 +- .../Doctrine/RemoveListenerTest.php | 4 +- .../Doctrine/UploadListenerTest.php | 8 ++-- .../Propel/CleanListenerTest.php | 2 +- .../Propel/InjectListenerTest.php | 2 +- .../Propel/RemoveListenerTest.php | 2 +- .../Propel/UploadListenerTest.php | 2 +- Tests/Handler/UploadHandlerTest.php | 44 +++++++++---------- 18 files changed, 49 insertions(+), 49 deletions(-) diff --git a/EventListener/Doctrine/CleanListener.php b/EventListener/Doctrine/CleanListener.php index 790786be..941a77f6 100644 --- a/EventListener/Doctrine/CleanListener.php +++ b/EventListener/Doctrine/CleanListener.php @@ -36,7 +36,7 @@ public function preUpdate(EventArgs $event) $object = $this->adapter->getObjectFromEvent($event); if ($this->metadata->isUploadable($this->adapter->getClassName($object))) { - $this->handler->handleCleaning($object, $this->mapping); + $this->handler->clean($object, $this->mapping); $this->adapter->recomputeChangeSet($event); } } diff --git a/EventListener/Doctrine/InjectListener.php b/EventListener/Doctrine/InjectListener.php index bed42fed..91692e8d 100644 --- a/EventListener/Doctrine/InjectListener.php +++ b/EventListener/Doctrine/InjectListener.php @@ -36,7 +36,7 @@ public function postLoad(EventArgs $event) $object = $this->adapter->getObjectFromEvent($event); if ($this->metadata->isUploadable($this->adapter->getClassName($object))) { - $this->handler->handleHydration($object, $this->mapping); + $this->handler->hydrate($object, $this->mapping); } } } diff --git a/EventListener/Doctrine/RemoveListener.php b/EventListener/Doctrine/RemoveListener.php index 2024fdab..7005660a 100644 --- a/EventListener/Doctrine/RemoveListener.php +++ b/EventListener/Doctrine/RemoveListener.php @@ -36,7 +36,7 @@ public function postRemove(EventArgs $event) $object = $this->adapter->getObjectFromEvent($event); if ($this->metadata->isUploadable($this->adapter->getClassName($object))) { - $this->handler->handleDeletion($object, $this->mapping); + $this->handler->delete($object, $this->mapping); } } } diff --git a/EventListener/Doctrine/UploadListener.php b/EventListener/Doctrine/UploadListener.php index f6806ab4..ad838b92 100644 --- a/EventListener/Doctrine/UploadListener.php +++ b/EventListener/Doctrine/UploadListener.php @@ -37,7 +37,7 @@ public function prePersist(EventArgs $event) $object = $this->adapter->getObjectFromEvent($event); if ($this->metadata->isUploadable($this->adapter->getClassName($object))) { - $this->handler->handleUpload($object, $this->mapping); + $this->handler->upload($object, $this->mapping); } } @@ -51,7 +51,7 @@ public function preUpdate(EventArgs $event) $object = $this->adapter->getObjectFromEvent($event); if ($this->metadata->isUploadable($this->adapter->getClassName($object))) { - $this->handler->handleUpload($object, $this->mapping); + $this->handler->upload($object, $this->mapping); $this->adapter->recomputeChangeSet($event); } } diff --git a/EventListener/Propel/CleanListener.php b/EventListener/Propel/CleanListener.php index ee8f5b93..63b3d36f 100644 --- a/EventListener/Propel/CleanListener.php +++ b/EventListener/Propel/CleanListener.php @@ -34,6 +34,6 @@ public static function getSubscribedEvents() public function onUpload(GenericEvent $event) { $object = $this->adapter->getObjectFromEvent($event); - $this->handler->handleCleaning($object, $this->mapping); + $this->handler->clean($object, $this->mapping); } } diff --git a/EventListener/Propel/InjectListener.php b/EventListener/Propel/InjectListener.php index 1db4285a..bcb15d5c 100644 --- a/EventListener/Propel/InjectListener.php +++ b/EventListener/Propel/InjectListener.php @@ -34,6 +34,6 @@ public static function getSubscribedEvents() public function onHydrate(GenericEvent $event) { $object = $this->adapter->getObjectFromEvent($event); - $this->handler->handleHydration($object, $this->mapping); + $this->handler->hydrate($object, $this->mapping); } } diff --git a/EventListener/Propel/RemoveListener.php b/EventListener/Propel/RemoveListener.php index 8797c478..5793ddbb 100644 --- a/EventListener/Propel/RemoveListener.php +++ b/EventListener/Propel/RemoveListener.php @@ -34,6 +34,6 @@ public static function getSubscribedEvents() public function onDelete(GenericEvent $event) { $object = $this->adapter->getObjectFromEvent($event); - $this->handler->handleDeletion($object, $this->mapping); + $this->handler->delete($object, $this->mapping); } } diff --git a/EventListener/Propel/UploadListener.php b/EventListener/Propel/UploadListener.php index 8daf34c6..96ed2a37 100644 --- a/EventListener/Propel/UploadListener.php +++ b/EventListener/Propel/UploadListener.php @@ -35,6 +35,6 @@ public static function getSubscribedEvents() public function onUpload(GenericEvent $event) { $object = $this->adapter->getObjectFromEvent($event); - $this->handler->handleUpload($object, $this->mapping); + $this->handler->upload($object, $this->mapping); } } diff --git a/Handler/UploadHandler.php b/Handler/UploadHandler.php index 8feb7b83..d7857e67 100644 --- a/Handler/UploadHandler.php +++ b/Handler/UploadHandler.php @@ -47,7 +47,7 @@ public function __construct(PropertyMappingFactory $factory, StorageInterface $s /** * Checks for file to upload. */ - public function handleUpload($object, $mapping) + public function upload($object, $mapping) { if (!$this->factory->hasMapping($object, $mapping)) { return; @@ -67,7 +67,7 @@ public function handleUpload($object, $mapping) /** * Checks for file to remove before a new upload. */ - public function handleCleaning($object, $mapping) + public function clean($object, $mapping) { if (!$this->factory->hasMapping($object, $mapping)) { return; @@ -86,7 +86,7 @@ public function handleCleaning($object, $mapping) } } - public function handleHydration($object, $mapping) + public function hydrate($object, $mapping) { if (!$this->factory->hasMapping($object, $mapping)) { return; @@ -96,7 +96,7 @@ public function handleHydration($object, $mapping) $this->injector->injectFiles($object, $mapping); } - public function handleDeletion($object, $mapping) + public function delete($object, $mapping) { if (!$this->factory->hasMapping($object, $mapping)) { return; diff --git a/Tests/EventListener/Doctrine/CleanListenerTest.php b/Tests/EventListener/Doctrine/CleanListenerTest.php index 9e3de1d4..8a53d02b 100644 --- a/Tests/EventListener/Doctrine/CleanListenerTest.php +++ b/Tests/EventListener/Doctrine/CleanListenerTest.php @@ -44,7 +44,7 @@ public function testPreUpdate() $this->handler ->expects($this->once()) - ->method('handleCleaning') + ->method('clean') ->with($this->object, self::MAPPING_NAME); $this->adapter @@ -69,7 +69,7 @@ public function testPreUpdateSkipsNonUploadable() $this->handler ->expects($this->never()) - ->method('handleCleaning'); + ->method('clean'); $this->adapter ->expects($this->never()) diff --git a/Tests/EventListener/Doctrine/InjectListenerTest.php b/Tests/EventListener/Doctrine/InjectListenerTest.php index a521173f..85372687 100644 --- a/Tests/EventListener/Doctrine/InjectListenerTest.php +++ b/Tests/EventListener/Doctrine/InjectListenerTest.php @@ -44,7 +44,7 @@ public function testPostLoad() $this->handler ->expects($this->once()) - ->method('handleHydration') + ->method('hydrate') ->with($this->object, self::MAPPING_NAME); $this->listener->postLoad($this->event); @@ -63,7 +63,7 @@ public function testPostLoadSkipsNonUploadable() $this->handler ->expects($this->never()) - ->method('handleHydration', self::MAPPING_NAME); + ->method('hydrate', self::MAPPING_NAME); $this->listener->postLoad($this->event); } diff --git a/Tests/EventListener/Doctrine/RemoveListenerTest.php b/Tests/EventListener/Doctrine/RemoveListenerTest.php index 2cee136c..938e1e86 100644 --- a/Tests/EventListener/Doctrine/RemoveListenerTest.php +++ b/Tests/EventListener/Doctrine/RemoveListenerTest.php @@ -44,7 +44,7 @@ public function testPostRemove() $this->handler ->expects($this->once()) - ->method('handleDeletion') + ->method('delete') ->with($this->object, self::MAPPING_NAME); $this->listener->postRemove($this->event); @@ -63,7 +63,7 @@ public function testPostRemoveSkipsNonUploadable() $this->handler ->expects($this->never()) - ->method('handleDeletion'); + ->method('delete'); $this->listener->postRemove($this->event); } diff --git a/Tests/EventListener/Doctrine/UploadListenerTest.php b/Tests/EventListener/Doctrine/UploadListenerTest.php index fb3bfc67..4bdde089 100644 --- a/Tests/EventListener/Doctrine/UploadListenerTest.php +++ b/Tests/EventListener/Doctrine/UploadListenerTest.php @@ -44,7 +44,7 @@ public function testPrePersist() $this->handler ->expects($this->once()) - ->method('handleUpload') + ->method('upload') ->with($this->object, self::MAPPING_NAME); $this->listener->prePersist($this->event); @@ -63,7 +63,7 @@ public function testPrePersistSkipsNonUploadable() $this->handler ->expects($this->never()) - ->method('handleUpload'); + ->method('upload'); $this->listener->prePersist($this->event); } @@ -86,7 +86,7 @@ public function testPreUpdate() $this->handler ->expects($this->once()) - ->method('handleUpload') + ->method('upload') ->with($this->object, self::MAPPING_NAME); $this->listener->preUpdate($this->event); @@ -109,7 +109,7 @@ public function testPreUpdateSkipsNonUploadable() $this->handler ->expects($this->never()) - ->method('handleUpload'); + ->method('upload'); $this->listener->preUpdate($this->event); } diff --git a/Tests/EventListener/Propel/CleanListenerTest.php b/Tests/EventListener/Propel/CleanListenerTest.php index 1774b2dc..1e5090df 100644 --- a/Tests/EventListener/Propel/CleanListenerTest.php +++ b/Tests/EventListener/Propel/CleanListenerTest.php @@ -35,7 +35,7 @@ public function testOnUpload() { $this->handler ->expects($this->once()) - ->method('handleCleaning') + ->method('clean') ->with($this->object, self::MAPPING_NAME); $this->listener->onUpload($this->event); diff --git a/Tests/EventListener/Propel/InjectListenerTest.php b/Tests/EventListener/Propel/InjectListenerTest.php index 99ec2a03..07830edd 100644 --- a/Tests/EventListener/Propel/InjectListenerTest.php +++ b/Tests/EventListener/Propel/InjectListenerTest.php @@ -35,7 +35,7 @@ public function testOnHydrate() { $this->handler ->expects($this->once()) - ->method('handleHydration') + ->method('hydrate') ->with($this->object, self::MAPPING_NAME); $this->listener->onHydrate($this->event); diff --git a/Tests/EventListener/Propel/RemoveListenerTest.php b/Tests/EventListener/Propel/RemoveListenerTest.php index 9bc26279..39b8411a 100644 --- a/Tests/EventListener/Propel/RemoveListenerTest.php +++ b/Tests/EventListener/Propel/RemoveListenerTest.php @@ -35,7 +35,7 @@ public function testOnDelete() { $this->handler ->expects($this->once()) - ->method('handleDeletion') + ->method('delete') ->with($this->object, self::MAPPING_NAME); $this->listener->onDelete($this->event); diff --git a/Tests/EventListener/Propel/UploadListenerTest.php b/Tests/EventListener/Propel/UploadListenerTest.php index d1a4595d..1a1b64f0 100644 --- a/Tests/EventListener/Propel/UploadListenerTest.php +++ b/Tests/EventListener/Propel/UploadListenerTest.php @@ -36,7 +36,7 @@ public function testOnUpload() { $this->handler ->expects($this->once()) - ->method('handleUpload') + ->method('upload') ->with($this->object, self::MAPPING_NAME); $this->listener->onUpload($this->event); diff --git a/Tests/Handler/UploadHandlerTest.php b/Tests/Handler/UploadHandlerTest.php index f864d3ed..7fa1d479 100644 --- a/Tests/Handler/UploadHandlerTest.php +++ b/Tests/Handler/UploadHandlerTest.php @@ -52,7 +52,7 @@ public function setUp() $this->handler = new UploadHandler($this->factory, $this->storage, $this->injector); } - public function testHandleUploadDoesNothingIfMappingDoesntExistForObject() + public function testUploadDoesNothingIfMappingDoesntExistForObject() { $this->factory ->expects($this->once()) @@ -68,13 +68,13 @@ public function testHandleUploadDoesNothingIfMappingDoesntExistForObject() ->expects($this->never()) ->method('injectFiles'); - $this->handler->handleUpload($this->object, 'dummy_mapping'); + $this->handler->upload($this->object, 'dummy_mapping'); } /** * @dataProvider invalidUploadedFileProvider */ - public function testHandleUploadDoesNothingIfNoFileIsUploaded($file) + public function testUploadDoesNothingIfNoFileIsUploaded($file) { $mapping = $this->getPropertyMappingMock(); @@ -104,10 +104,10 @@ public function testHandleUploadDoesNothingIfNoFileIsUploaded($file) ->expects($this->never()) ->method('injectFiles'); - $this->handler->handleUpload($this->object, 'dummy_mapping'); + $this->handler->upload($this->object, 'dummy_mapping'); } - public function testHandleUpload() + public function testUpload() { $file = $this->getMockBuilder('Symfony\Component\HttpFoundation\File\UploadedFile') ->disableOriginalConstructor() @@ -143,10 +143,10 @@ public function testHandleUpload() ->method('injectFiles') ->with($this->object, $mapping); - $this->handler->handleUpload($this->object, 'dummy_mapping'); + $this->handler->upload($this->object, 'dummy_mapping'); } - public function testHandleCleaningDoesNothingIfMappingDoesntExistForObject() + public function testCleanDoesNothingIfMappingDoesntExistForObject() { $this->factory ->expects($this->once()) @@ -158,10 +158,10 @@ public function testHandleCleaningDoesNothingIfMappingDoesntExistForObject() ->expects($this->never()) ->method('remove'); - $this->handler->handleCleaning($this->object, 'dummy_mapping'); + $this->handler->clean($this->object, 'dummy_mapping'); } - public function testHandleCleaningDoesNothingIfNoOldFileIsPresent() + public function testCleanDoesNothingIfNoOldFileIsPresent() { $file = $this->getMockBuilder('Symfony\Component\HttpFoundation\File\UploadedFile') ->disableOriginalConstructor() @@ -196,13 +196,13 @@ public function testHandleCleaningDoesNothingIfNoOldFileIsPresent() ->expects($this->never()) ->method('remove'); - $this->handler->handleCleaning($this->object, 'dummy_mapping'); + $this->handler->clean($this->object, 'dummy_mapping'); } /** * @dataProvider invalidUploadedFileProvider */ - public function testHandleCleaningDoesNothingIfNoFileIsUploaded($file) + public function testCleanDoesNothingIfNoFileIsUploaded($file) { $mapping = $this->getPropertyMappingMock(); @@ -228,7 +228,7 @@ public function testHandleCleaningDoesNothingIfNoFileIsUploaded($file) ->expects($this->never()) ->method('remove'); - $this->handler->handleCleaning($this->object, 'dummy_mapping'); + $this->handler->clean($this->object, 'dummy_mapping'); } public function invalidUploadedFileProvider() @@ -245,7 +245,7 @@ public function invalidUploadedFileProvider() ); } - public function testHandleCleaning() + public function testClean() { $file = $this->getMockBuilder('Symfony\Component\HttpFoundation\File\UploadedFile') ->disableOriginalConstructor() @@ -281,10 +281,10 @@ public function testHandleCleaning() ->method('remove') ->with($this->object, $mapping); - $this->handler->handleCleaning($this->object, 'dummy_mapping'); + $this->handler->clean($this->object, 'dummy_mapping'); } - public function testHandleHydrationDoesNothingIfMappingDoesntExistForObject() + public function testHydrateDoesNothingIfMappingDoesntExistForObject() { $this->factory ->expects($this->once()) @@ -296,10 +296,10 @@ public function testHandleHydrationDoesNothingIfMappingDoesntExistForObject() ->expects($this->never()) ->method('injectFiles'); - $this->handler->handleHydration($this->object, 'dummy_mapping'); + $this->handler->hydrate($this->object, 'dummy_mapping'); } - public function testHandleHydration() + public function testHydrate() { $mapping = $this->getPropertyMappingMock(); @@ -320,10 +320,10 @@ public function testHandleHydration() ->method('injectFiles') ->with($this->object, $mapping); - $this->handler->handleHydration($this->object, 'dummy_mapping'); + $this->handler->hydrate($this->object, 'dummy_mapping'); } - public function testHandleDeletionDoesNothingIfMappingDoesntExistForObject() + public function testDeleteDoesNothingIfMappingDoesntExistForObject() { $this->factory ->expects($this->once()) @@ -335,10 +335,10 @@ public function testHandleDeletionDoesNothingIfMappingDoesntExistForObject() ->expects($this->never()) ->method('remove'); - $this->handler->handleDeletion($this->object, 'dummy_mapping'); + $this->handler->delete($this->object, 'dummy_mapping'); } - public function testHandleDeletion() + public function testDelete() { $mapping = $this->getPropertyMappingMock(); @@ -359,7 +359,7 @@ public function testHandleDeletion() ->method('remove') ->with($this->object, $mapping); - $this->handler->handleDeletion($this->object, 'dummy_mapping'); + $this->handler->delete($this->object, 'dummy_mapping'); } /** From 98c3e3cd9125562475da4d0aea12bc2316ff2e34 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Wed, 25 Dec 2013 18:59:01 +0100 Subject: [PATCH 51/54] Renamed FileInjector::injectFiles method to injectFile --- Handler/UploadHandler.php | 4 ++-- Injector/FileInjector.php | 2 +- Injector/FileInjectorInterface.php | 2 +- Tests/Handler/UploadHandlerTest.php | 10 +++++----- Tests/Injector/FileInjectorTest.php | 4 ++-- 5 files changed, 11 insertions(+), 11 deletions(-) diff --git a/Handler/UploadHandler.php b/Handler/UploadHandler.php index d7857e67..829e7ef6 100644 --- a/Handler/UploadHandler.php +++ b/Handler/UploadHandler.php @@ -61,7 +61,7 @@ public function upload($object, $mapping) } $this->storage->upload($object, $mapping); - $this->injector->injectFiles($object, $mapping); + $this->injector->injectFile($object, $mapping); } /** @@ -93,7 +93,7 @@ public function hydrate($object, $mapping) } $mapping = $this->factory->fromName($object, $mapping); - $this->injector->injectFiles($object, $mapping); + $this->injector->injectFile($object, $mapping); } public function delete($object, $mapping) diff --git a/Injector/FileInjector.php b/Injector/FileInjector.php index db421e6f..305b975d 100644 --- a/Injector/FileInjector.php +++ b/Injector/FileInjector.php @@ -33,7 +33,7 @@ public function __construct(StorageInterface $storage) /** * {@inheritDoc} */ - public function injectFiles($object, PropertyMapping $mapping) + public function injectFile($object, PropertyMapping $mapping) { $field = $mapping->getFilePropertyName(); diff --git a/Injector/FileInjectorInterface.php b/Injector/FileInjectorInterface.php index 804b56af..e312b903 100644 --- a/Injector/FileInjectorInterface.php +++ b/Injector/FileInjectorInterface.php @@ -19,5 +19,5 @@ interface FileInjectorInterface * @param object $object The object. * @param PropertyMapping $mapping The mapping representing the field to populate. */ - public function injectFiles($object, PropertyMapping $mapping); + public function injectFile($object, PropertyMapping $mapping); } diff --git a/Tests/Handler/UploadHandlerTest.php b/Tests/Handler/UploadHandlerTest.php index 7fa1d479..4c7ade74 100644 --- a/Tests/Handler/UploadHandlerTest.php +++ b/Tests/Handler/UploadHandlerTest.php @@ -66,7 +66,7 @@ public function testUploadDoesNothingIfMappingDoesntExistForObject() $this->injector ->expects($this->never()) - ->method('injectFiles'); + ->method('injectFile'); $this->handler->upload($this->object, 'dummy_mapping'); } @@ -102,7 +102,7 @@ public function testUploadDoesNothingIfNoFileIsUploaded($file) $this->injector ->expects($this->never()) - ->method('injectFiles'); + ->method('injectFile'); $this->handler->upload($this->object, 'dummy_mapping'); } @@ -140,7 +140,7 @@ public function testUpload() $this->injector ->expects($this->once()) - ->method('injectFiles') + ->method('injectFile') ->with($this->object, $mapping); $this->handler->upload($this->object, 'dummy_mapping'); @@ -294,7 +294,7 @@ public function testHydrateDoesNothingIfMappingDoesntExistForObject() $this->injector ->expects($this->never()) - ->method('injectFiles'); + ->method('injectFile'); $this->handler->hydrate($this->object, 'dummy_mapping'); } @@ -317,7 +317,7 @@ public function testHydrate() $this->injector ->expects($this->once()) - ->method('injectFiles') + ->method('injectFile') ->with($this->object, $mapping); $this->handler->hydrate($this->object, 'dummy_mapping'); diff --git a/Tests/Injector/FileInjectorTest.php b/Tests/Injector/FileInjectorTest.php index 284dd4f7..f84629ec 100644 --- a/Tests/Injector/FileInjectorTest.php +++ b/Tests/Injector/FileInjectorTest.php @@ -72,7 +72,7 @@ public function testInjectsOneFile() ->with($this->equalTo($obj), $this->equalTo($filePropertyName)) ->will($this->returnValue($this->getUploadDir() . DIRECTORY_SEPARATOR . 'file.txt')); - $this->injector->injectFiles($obj, $fileMapping); + $this->injector->injectFile($obj, $fileMapping); } public function testPropertyIsNullWhenFileNamePropertyIsNull() @@ -93,7 +93,7 @@ public function testPropertyIsNullWhenFileNamePropertyIsNull() ->method('resolvePath') ->will($this->throwException(new \InvalidArgumentException)); - $this->injector->injectFiles($obj, $fileMapping); + $this->injector->injectFile($obj, $fileMapping); } /** From aef9ed9d7f079beb16af952dafe0c966477e1550 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Thu, 26 Dec 2013 13:38:06 +0000 Subject: [PATCH 52/54] Gave a more precise version constraint for Propel --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 00c43a3f..a2fb8c2d 100644 --- a/composer.json +++ b/composer.json @@ -24,7 +24,7 @@ "doctrine/mongodb-odm": "@dev", "knplabs/knp-gaufrette-bundle": "*", "phpunit/phpunit": "~3.7", - "propel/propel1": "~1", + "propel/propel1": ">=1.6", "willdurand/propel-eventdispatcher-bundle": "~1.0", "symfony/yaml": "@stable" }, From 89efe45474772c4fff374dd861f4578e4f36f03f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Thu, 26 Dec 2013 14:38:38 +0000 Subject: [PATCH 53/54] Raised the minimum symfony version to 2.1 --- .travis.yml | 1 - DependencyInjection/VichUploaderExtension.php | 5 ----- composer.json | 4 ++-- 3 files changed, 2 insertions(+), 8 deletions(-) diff --git a/.travis.yml b/.travis.yml index e0d73070..bce20cb9 100644 --- a/.travis.yml +++ b/.travis.yml @@ -7,7 +7,6 @@ php: - hhvm env: - - SYMFONY_VERSION="~2.0.0" DOCTRINE_VERSION="~2.2.0" - SYMFONY_VERSION="~2.1.0" DOCTRINE_VERSION=">=2.2.3,<2.5-dev" - SYMFONY_VERSION="~2.2.0" DOCTRINE_VERSION="~2.2,>=2.2.3" - SYMFONY_VERSION="~2.3.0" DOCTRINE_VERSION=">=2.2.3,<2.4-dev" diff --git a/DependencyInjection/VichUploaderExtension.php b/DependencyInjection/VichUploaderExtension.php index be40da0f..5e5cae1f 100644 --- a/DependencyInjection/VichUploaderExtension.php +++ b/DependencyInjection/VichUploaderExtension.php @@ -33,11 +33,6 @@ class VichUploaderExtension extends Extension */ public function load(array $configs, ContainerBuilder $container) { - // Set correct doctrine subscriber event for versions of symfony before 2.1 - if (!defined('Symfony\Component\HttpKernel\Kernel::VERSION_ID') || Kernel::VERSION_ID < 20100) { - $this->tagMap['mongodb'] = 'doctrine.odm.mongodb.event_subscriber'; - } - $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); diff --git a/composer.json b/composer.json index a2fb8c2d..6fa846bb 100644 --- a/composer.json +++ b/composer.json @@ -13,10 +13,10 @@ ], "require": { "php": ">=5.3.2", - "symfony/framework-bundle": "~2.0", + "symfony/framework-bundle": "~2.1", "jms/metadata": "~1.5", "symfony/property-access": ">=2.2,<3.0", - "symfony/finder": ">=2.0" + "symfony/finder": "~2.0" }, "require-dev": { "mikey179/vfsStream": "~1.0", From 335aaf6482e010aa79fddab50b2e7196112e1cee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Thu, 26 Dec 2013 15:02:18 +0000 Subject: [PATCH 54/54] Added myself to the authors --- composer.json | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/composer.json b/composer.json index 6fa846bb..4b78214f 100644 --- a/composer.json +++ b/composer.json @@ -9,6 +9,10 @@ { "name": "Dustin Dobervich", "email": "ddobervich@gmail.com" + }, + { + "name": "Kévin Gomez", + "email": "contact@kevingomez.fr" } ], "require": {