Exemplo n.º 1
0
 /**
  * {@inheritdoc}
  */
 public function generateUrl(StoredFile $storedFile)
 {
     $storageKey = $storedFile->getStorageKey();
     $storageKey .= '/' . $storedFile->getRepository()->getName();
     $storageKey .= '/' . $storedFile->getFilename();
     return $this->router->generate($this->routeName, array('storageKey' => $storageKey), RouterInterface::NETWORK_PATH);
 }
Exemplo n.º 2
0
 public function testGetUrl()
 {
     $container = \Phake::mock('Symfony\\Component\\DependencyInjection\\ContainerInterface');
     \Phake::when($container)->getParameter(ModeraFileRepositoryExtension::CONFIG_KEY . '.default_url_generator')->thenReturn('default_url_generator');
     \Phake::when($container)->getParameter(ModeraFileRepositoryExtension::CONFIG_KEY . '.url_generators')->thenReturn(array('foo' => 'foo_url_generator', 'bar' => 'bar_url_generator'));
     $defaultUrlGenerator = \Phake::mock('Modera\\FileRepositoryBundle\\StoredFile\\UrlGeneratorInterface');
     \Phake::when($container)->get('default_url_generator')->thenReturn($defaultUrlGenerator);
     $fooUrlGenerator = \Phake::mock('Modera\\FileRepositoryBundle\\StoredFile\\UrlGeneratorInterface');
     \Phake::when($container)->get('foo_url_generator')->thenReturn($fooUrlGenerator);
     \Phake::when($container)->get('bar_url_generator')->thenReturn('not_url_generator');
     $context = array();
     $splFile = new \SplFileInfo(__FILE__);
     $repository = \Phake::mock('Modera\\FileRepositoryBundle\\Entity\\Repository');
     \Phake::when($repository)->generateStorageKey($splFile, $context)->thenReturn('storage-key');
     $storedFile = new StoredFile($repository, $splFile, $context);
     $storedFile->init($container);
     \Phake::when($defaultUrlGenerator)->generateUrl($storedFile)->thenReturn('default_url');
     \Phake::when($fooUrlGenerator)->generateUrl($storedFile)->thenReturn('foo_url');
     \Phake::when($repository)->getConfig()->thenReturn(array('filesystem' => 'foo'));
     $this->assertEquals('foo_url', $storedFile->getUrl());
     \Phake::when($repository)->getConfig()->thenReturn(array('filesystem' => 'bar'));
     $this->assertEquals('default_url', $storedFile->getUrl());
     \Phake::when($repository)->getConfig()->thenReturn(array('filesystem' => 'baz'));
     $this->assertEquals('default_url', $storedFile->getUrl());
 }
Exemplo n.º 3
0
 public function testInterceptors()
 {
     $itc = new DummyInterceptor();
     $interceptorsProvider = \Phake::mock('Modera\\FileRepositoryBundle\\Intercepting\\InterceptorsProviderInterface');
     \Phake::when($interceptorsProvider)->getInterceptors($this->isInstanceOf(Repository::clazz()))->thenReturn([$itc]);
     $container = \Phake::mock('Symfony\\Component\\DependencyInjection\\ContainerInterface');
     \Phake::when($container)->get('modera_file_repository.intercepting.interceptors_provider')->thenReturn($interceptorsProvider);
     $repository = new Repository('foo', array('filesystem' => 'foo'));
     $repository->init($container);
     $splFile = new \SplFileInfo(__FILE__);
     $storedFile = \Phake::mock(StoredFile::clazz());
     // ---
     $this->assertEquals(0, count($itc->beforePutInvocations));
     $repository->beforePut($splFile);
     $this->assertEquals(1, count($itc->beforePutInvocations));
     $this->assertSame($splFile, $itc->beforePutInvocations[0][0]);
     $this->assertSame($repository, $itc->beforePutInvocations[0][1]);
     // ---
     $receivedInterceptor = null;
     $repository->beforePut($splFile, function ($interceptor) use(&$receivedInterceptor) {
         $receivedInterceptor = $interceptor;
         return false;
     });
     $this->assertSame($itc, $receivedInterceptor);
     $this->assertEquals(1, count($itc->beforePutInvocations));
     // ---
     $this->assertEquals(0, count($itc->onPutInvocations));
     $repository->onPut($storedFile, $splFile);
     $this->assertEquals(1, count($itc->onPutInvocations));
     $this->assertSame($storedFile, $itc->onPutInvocations[0][0]);
     $this->assertSame($splFile, $itc->onPutInvocations[0][1]);
     $this->assertSame($repository, $itc->onPutInvocations[0][2]);
     // ---
     $receivedInterceptor = null;
     $repository->onPut($storedFile, $splFile, function ($interceptor) use(&$receivedInterceptor) {
         $receivedInterceptor = $interceptor;
         return false;
     });
     $this->assertSame($itc, $receivedInterceptor);
     $this->assertEquals(1, count($itc->onPutInvocations));
     // ---
     $this->assertEquals(0, count($itc->afterPutInvocations));
     $repository->afterPut($storedFile, $splFile);
     $this->assertEquals(1, count($itc->afterPutInvocations));
     $this->assertSame($storedFile, $itc->afterPutInvocations[0][0]);
     $this->assertSame($splFile, $itc->afterPutInvocations[0][1]);
     $this->assertSame($repository, $itc->afterPutInvocations[0][2]);
     $receivedInterceptor = null;
     $repository->afterPut($storedFile, $splFile, function ($interceptor) use(&$receivedInterceptor) {
         $receivedInterceptor = $interceptor;
         return false;
     });
     $this->assertSame($itc, $receivedInterceptor);
     $this->assertEquals(1, count($itc->afterPutInvocations));
 }
Exemplo n.º 4
0
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     /* @var EntityManager $em */
     $em = $this->getContainer()->get('doctrine.orm.entity_manager');
     /* @var StoredFile $storedFile */
     $storedFile = $em->find(StoredFile::clazz(), $input->getArgument('file_id'));
     if (!$storedFile) {
         throw new \RuntimeException('Unable to find a file with ID ' . $input->getArgument('file_id'));
     }
     $output->writeln(sprintf('Deleting file "%s" from repository "%s"', $storedFile->getFilename(), $storedFile->getRepository()->getName()));
     $em->remove($storedFile);
     $em->flush();
     $output->writeln('<info>Done!</info>');
 }
Exemplo n.º 5
0
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     /* @var EntityManager $em */
     $em = $this->getContainer()->get('doctrine.orm.entity_manager');
     /* @var StoredFile $storedFile */
     $storedFile = $em->getRepository(StoredFile::clazz())->find($input->getArgument('file_id'));
     if (!$storedFile) {
         throw new \RuntimeException(sprintf('Unable to find a file with ID "%s".', $input->getArgument('file_id')));
     }
     $localPath = $input->getArgument('local_path');
     $output->writeln('Downloading the file ...');
     ob_start();
     $result = file_put_contents($localPath, $storedFile->getContents());
     $errorOutput = ob_get_clean();
     if (false !== $result) {
         $output->writeln(sprintf('<info>File from repository "%s" has been successfully downloaded and stored locally at %s</info>', $storedFile->getRepository()->getName(), $localPath));
     } else {
         $output->writeln('<error>Something went wrong, we were unable to save a file locally: </error>');
         $output->writeln($errorOutput);
     }
 }
 private function createStoredFile($storageKey, $content)
 {
     if ($storageKey) {
         $parts = explode('/', $storageKey);
         if (count($parts) > 1) {
             $filename = $parts[count($parts) - 1];
         } else {
             $filename = 'foo.txt';
         }
         list($name, $extension) = explode('.', $filename);
         $mimeType = array('txt' => 'text/plain');
         $storedFile = \Phake::mock(StoredFile::clazz());
         \Phake::when($storedFile)->getStorageKey()->thenReturn($parts[0]);
         \Phake::when($storedFile)->getFilename()->thenReturn($filename);
         \Phake::when($storedFile)->getMimeType()->thenReturn($mimeType[$extension]);
         \Phake::when($storedFile)->getExtension()->thenReturn($extension);
         \Phake::when($storedFile)->getCreatedAt()->thenReturn(new \DateTime());
         \Phake::when($storedFile)->getContents()->thenReturn($content);
         \Phake::when($storedFile)->getSize()->thenReturn(strlen($content));
         return $storedFile;
     }
     return;
 }
 private function assertValidAlternative($expectedName, $expectedWidth, $expectedHeight, StoredFile $storedFile)
 {
     $this->assertEquals($expectedName, $storedFile->getFilename());
     $meta = $storedFile->getMeta();
     $this->assertArrayHasKey('thumbnail', $meta);
     $this->assertArrayHasKey('width', $meta['thumbnail']);
     $this->assertEquals($expectedWidth, $meta['thumbnail']['width']);
     $this->assertArrayHasKey('height', $meta['thumbnail']);
     $this->assertEquals($expectedHeight, $meta['thumbnail']['height']);
     $tmpFile = tempnam(sys_get_temp_dir(), 'image_');
     file_put_contents($tmpFile, $storedFile->getContents());
     $imagine = new Imagine();
     $image = $imagine->open($tmpFile);
     $this->assertEquals($expectedWidth, $image->getSize()->getWidth());
 }
Exemplo n.º 8
0
 public function testHowWellItWorks()
 {
     /* @var FileRepository $fr */
     $fr = self::$container->get('modera_file_repository.repository.file_repository');
     $this->assertNull($fr->getRepository('dummy_repository'));
     $repositoryConfig = array('storage_key_generator' => 'modera_file_repository.repository.uniqid_key_generator', 'filesystem' => 'dummy_tmp_fs');
     $this->assertFalse($fr->repositoryExists('dummy_repository'));
     $repository = $fr->createRepository('dummy_repository', $repositoryConfig, 'My dummy repository');
     $this->assertTrue($fr->repositoryExists('dummy_repository'));
     $this->assertInstanceOf(Repository::clazz(), $repository);
     $this->assertNotNull($repository->getId());
     $this->assertEquals('dummy_repository', $repository->getName());
     $this->assertEquals('My dummy repository', $repository->getLabel());
     $this->assertSame($repositoryConfig, $repository->getConfig());
     $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\ContainerInterface', Toolkit::getPropertyValue($repository, 'container'));
     // ---
     $fileContents = 'foo contents';
     $filePath = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'our-dummy-file.txt';
     file_put_contents($filePath, $fileContents);
     $file = new File($filePath);
     $storedFile = $fr->put($repository->getName(), $file, array());
     self::$em->clear();
     // this way we will make sure that data is actually persisted in database
     /* @var StoredFile $storedFile */
     $storedFile = self::$em->find(StoredFile::clazz(), $storedFile->getId());
     $this->assertInstanceOf(StoredFile::clazz(), $storedFile);
     $this->assertNotNull($storedFile->getId());
     $this->assertNotNull($storedFile->getStorageKey());
     $this->assertEquals('our-dummy-file.txt', $storedFile->getFilename());
     $this->assertNotNull($storedFile->getCreatedAt());
     $this->assertEquals('txt', $storedFile->getExtension());
     $this->assertEquals('text/plain', $storedFile->getMimeType());
     $this->assertSame($repository->getId(), $storedFile->getRepository()->getId());
     $this->assertEquals($fileContents, $storedFile->getContents());
     $this->assertTrue('' != $storedFile->getChecksum());
     $this->assertEquals($file->getSize(), $storedFile->getSize());
     // ---
     $storedFileData = array('id' => $storedFile->getId(), 'storageKey' => $storedFile->getStorageKey(), 'filename' => $storedFile->getFilename());
     $fileContents = 'bar contents';
     $filePath = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'bar-dummy-file.txt';
     file_put_contents($filePath, $fileContents);
     $file = new File($filePath);
     $storedFile = $fr->put($repository->getName(), $file, array());
     self::$em->clear();
     // this way we will make sure that data is actually persisted in database
     /* @var StoredFile $storedFile */
     $storedFile = self::$em->find(StoredFile::clazz(), $storedFile->getId());
     $this->assertNotEquals($storedFileData['id'], $storedFile->getId());
     $this->assertNotEquals($storedFileData['storageKey'], $storedFile->getStorageKey());
     $this->assertNotEquals($storedFileData['filename'], $storedFile->getFilename());
     // ---
     $repositoryConfig['overwrite_files'] = true;
     $repository = $storedFile->getRepository();
     $repository->setConfig($repositoryConfig);
     self::$em->persist($repository);
     self::$em->flush();
     $storedFileData = array('id' => $storedFile->getId(), 'storageKey' => $storedFile->getStorageKey(), 'filename' => $storedFile->getFilename());
     $storedFile = $fr->put($repository->getName(), $file, array());
     self::$em->clear();
     // this way we will make sure that data is actually persisted in database
     /* @var StoredFile $storedFile */
     $storedFile = self::$em->find(StoredFile::clazz(), $storedFile->getId());
     $this->assertEquals($storedFileData['id'], $storedFile->getId());
     $this->assertEquals($storedFileData['storageKey'], $storedFile->getStorageKey());
     $this->assertEquals($storedFileData['filename'], $storedFile->getFilename());
     // ---
     $fs = $storedFile->getRepository()->getFilesystem();
     $this->assertTrue($fs->has($storedFile->getStorageKey()));
     self::$em->remove($storedFile);
     self::$em->flush();
     $this->assertFalse($fs->has($storedFile->getStorageKey()));
 }
Exemplo n.º 9
0
 /**
  * @throws \RuntimeException
  *
  * @param $repositoryName
  * @param \SplFileInfo $file
  * @param array        $context
  *
  * @return \Modera\FileRepositoryBundle\Entity\StoredFile
  */
 public function put($repositoryName, \SplFileInfo $file, array $context = array())
 {
     $repository = $this->getRepository($repositoryName);
     if (!$repository) {
         throw new \RuntimeException("Unable to find repository '{$repositoryName}'.");
     }
     $config = $repository->getConfig();
     if (!$this->isInterceptorDisabled($context, 'before')) {
         $repository->beforePut($file, $this->createInterceptorsFilter($context, 'before'));
     }
     $storedFile = null;
     $overwrite = isset($config['overwrite_files']) ? $config['overwrite_files'] : false;
     if ($overwrite) {
         $filename = $file->getFilename();
         if ($file instanceof UploadedFile) {
             $filename = $file->getClientOriginalName();
         }
         /* @var StoredFile $storedFile */
         $storedFile = $this->em->getRepository(StoredFile::clazz())->findOneBy(array('repository' => $repository->getId(), 'filename' => $filename));
         if ($storedFile) {
             $storedFile->setCreatedAt(new \DateTime('now'));
         } else {
             $overwrite = false;
         }
     }
     if (!$storedFile) {
         $storedFile = $repository->createFile($file, $context);
     }
     $contents = @file_get_contents($file->getPathname());
     if (false === $contents) {
         throw new \RuntimeException(sprintf('Unable to read contents of "%s" file!', $file->getPath()));
     }
     if (!$this->isInterceptorDisabled($context, 'put')) {
         $repository->onPut($storedFile, $file, $this->createInterceptorsFilter($context, 'put'));
     }
     $storageKey = $storedFile->getStorageKey();
     /* @var Filesystem $fs */
     $fs = $repository->getFilesystem();
     // physically stored file
     $fs->write($storageKey, $contents, $overwrite);
     try {
         $this->em->persist($storedFile);
         $this->em->flush($storedFile);
     } catch (\Exception $e) {
         if (!$storedFile->getId()) {
             $fs->delete($storageKey);
         }
         throw $e;
     }
     if (!$this->isInterceptorDisabled($context, 'after')) {
         $repository->afterPut($storedFile, $file, $this->createInterceptorsFilter($context, 'after'));
     }
     return $storedFile;
 }
Exemplo n.º 10
0
 /**
  * This method is going to be invoked recursively to generate thumbnails, classes with AlternativeFileTrait are
  * going to serve as markers that thumbnail needs to be generated.
  *
  * {@inheritdoc}
  */
 public function onPut(StoredFile $storedFile, \SplFileInfo $file, Repository $repository)
 {
     $repoConfig = $storedFile->getRepository()->getConfig();
     if (!isset($repoConfig['thumbnail_sizes']) || count($repoConfig['thumbnail_sizes']) == 0) {
         return self::RESULT_NO_CONFIG_AVAILABLE;
     }
     $isAlternative = $this->isAlternative($file);
     // given $storedFile and $file could be alternative already so we need to resolve
     // an original file that we are going to use to generate a thumbnail from
     if ($isAlternative) {
         /* @var AlternativeFileTrait $file */
         $originalStoredFile = $file->getOriginalStoredFile();
         $originalFile = $file->getOriginalFile();
         $originalStoredFile->addAlternative($storedFile);
     } else {
         $originalStoredFile = $storedFile;
         $originalFile = $file;
     }
     if (!$originalFile instanceof File) {
         // "File" class provides the API we need (like guessing MIME type)
         $originalFile = new File($originalFile->getPathname());
     }
     $isImage = substr($originalFile->getMimeType(), 0, strlen('image/')) == 'image/';
     if (!$isImage) {
         return self::RESULT_NOT_IMAGE_GIVEN;
     }
     $lookupKey = $originalFile->getPathname();
     if (!isset($this->thumbnailsProgress[$lookupKey])) {
         $this->thumbnailsProgress[$lookupKey] = $repoConfig['thumbnail_sizes'];
         // thumbnails that have yet to be generated
     }
     if ($isAlternative) {
         // Taking a config of previously generated thumbnail and updating entity to store it.
         // We couldn't update it right away when we generate a thumbnail because we haven't yet
         // had access to entity
         $this->thumbnailsGenerator->updateStoredFileAlternativeMeta($storedFile, $file->getThumbnailConfig());
     }
     // getting next thumbnail's config that needs to be generated
     $thumbnailConfig = array_shift($this->thumbnailsProgress[$lookupKey]);
     if (!$thumbnailConfig) {
         // making it possible to have thumbnails generated if the same original file is passed to file
         // repository
         unset($this->thumbnailsProgress[$lookupKey]);
         return self::RESULT_NO_MORE_THUMBNAILS;
     }
     $thumbnailPathname = $this->generateThumbnail($originalFile, $storedFile, $thumbnailConfig);
     /* @var AlternativeFileTrait $newFile */
     $newFile = null;
     if ($originalFile instanceof UploadedFile) {
         $newFile = new AlternativeUploadedFile($thumbnailPathname, $originalFile->getClientOriginalName(), $originalFile->getClientMimeType(), filesize($thumbnailPathname));
     } else {
         $newFile = new AlternativeFile($thumbnailPathname);
     }
     $newFile->setOriginalFile($originalFile);
     $newFile->setOriginalStoredFile($originalStoredFile);
     $newFile->setThumbnailConfig($thumbnailConfig);
     // recursively creating thumbnails
     $this->fileRepository->put($repository->getName(), $newFile);
     // ... we cannot modify returned storedFile here already because UoW is already flushed
     return self::RESULT_SCHEDULED;
 }
Exemplo n.º 11
0
 /**
  * @param StoredFile $alternative
  * @param array      $thumbnailConfig
  */
 public function updateStoredFileAlternativeMeta(StoredFile $alternative, array $thumbnailConfig)
 {
     $alternative->mergeMeta(array('thumbnail' => $thumbnailConfig));
 }
Exemplo n.º 12
0
 /**
  * @param string $storageKey
  *
  * @return null|StoredFile
  */
 protected function getFile($storageKey)
 {
     /* @var ObjectRepository $repository */
     $repository = $this->getDoctrine()->getManager()->getRepository(StoredFile::clazz());
     return $repository->findOneBy(array('storageKey' => $storageKey));
 }
Exemplo n.º 13
0
 /**
  * @param \SplFileInfo $file
  * @param array        $context
  *
  * @return StoredFile
  */
 public function createFile(\SplFileInfo $file, array $context = array())
 {
     $result = new StoredFile($this, $file, $context);
     $result->init($this->container);
     $this->files->add($result);
     return $result;
 }