guessExtension() public méthode

If the mime type is unknown, returns null.
public guessExtension ( ) : string | null
Résultat string | null The guessed extension or null if it cannot be guessed
 public function preUpload()
 {
     if (null !== $this->photo_file) {
         // do whatever you want to generate a unique name
         $this->nom = $this->getUser()->getUsername() . '.' . $this->photo_file->guessExtension();
     }
 }
 public function preUpload()
 {
     if (null !== $this->file) {
         // do whatever you want to generate a unique name
         $this->file_name = $this->file->getClientOriginalName();
         $this->charte_file = uniqid() . '.' . $this->file->guessExtension();
     }
 }
Exemple #3
0
 /**
  * @requires extension fileinfo
  */
 public function testGuessExtensionWithReset()
 {
     $file = new File(__DIR__ . '/Fixtures/other-file.example');
     $guesser = $this->createMockGuesser($file->getPathname(), 'image/gif');
     MimeTypeGuesser::getInstance()->register($guesser);
     $this->assertEquals('gif', $file->guessExtension());
     MimeTypeGuesser::reset();
     $this->assertNull($file->guessExtension());
 }
Exemple #4
0
 /**
  * @throws FileException
  */
 public function upload()
 {
     if ($this->file instanceof File) {
         $name = sha1($this->file->getClientOriginalName() . uniqid() . getrandmax()) . '.' . $this->file->guessExtension();
         $this->file->move($this->getWeb() . $this->folder, $name);
         $this->file = $name;
     } else {
         throw new FileException('It must be a Symfony\\Component\\HttpFoundation\\File\\File instance');
     }
 }
Exemple #5
0
 public function testGuessExtensionIsBasedOnMimeType()
 {
     $file = new File(__DIR__ . '/Fixtures/test');
     $guesser = $this->createMockGuesser($file->getPathname(), 'image/gif');
     MimeTypeGuesser::getInstance()->register($guesser);
     $this->assertEquals('gif', $file->guessExtension());
 }
 /**
  * @param Contribution $contribution
  * @param File         $file
  *
  * @return string
  */
 public function generateRelativePath(Contribution $contribution, File $file)
 {
     $path = $contribution->getAuthProvider() . DIRECTORY_SEPARATOR;
     $path .= $contribution->getIdentifier();
     $path .= '.' . ($file->guessExtension() ?: $file->getExtension());
     return $path;
 }
 private function regenerateSpeakerPhotoPath($speaker)
 {
     // If speaker photo does not exist, null it out and return.
     if (!$this->fileExists($speaker['photo_path'])) {
         echo "[info] {$speaker['name']}'s photo was not found in file system. Removing record of it from profile." . PHP_EOL;
         $this->execute("UPDATE users SET photo_path = '' WHERE id = {$speaker['id']}");
         return;
     }
     // Need to guess extension. Cannot trust current file extensions.
     $file = new File(__DIR__ . '/../web/uploads/' . $speaker['photo_path']);
     $extension = $file->guessExtension();
     // Otherwise, generate a new filename.
     $generator = new PseudoRandomStringGenerator(new Factory());
     $newFileName = $generator->generate(40) . '.' . $extension;
     $oldFilePath = __DIR__ . '/../web/uploads/' . $speaker['photo_path'];
     $newFilePath = __DIR__ . '/../web/uploads/' . $newFileName;
     // If photo name is changed in file system, update record in database.
     if (rename($oldFilePath, $newFilePath)) {
         try {
             $this->execute("UPDATE users SET photo_path = '{$newFileName}' WHERE id = '{$speaker['id']}'");
             echo "[info] Regenerated photo path for {$speaker['name']}." . PHP_EOL;
         } catch (\Exception $e) {
             // If update fails for any reason, revert filename in file system.
             rename($newFilePath, $oldFilePath);
         }
     }
 }
Exemple #8
0
 /**
  * Handles image upload and resize
  *
  * @param string $context
  * @param File $uploadedFile
  * @param string $fileName
  * @param bool $useHashAsFilename
  *
  * @return string
  */
 public function upload($context, File $uploadedFile, $fileName = null, $useHashAsFilename = null)
 {
     if (null === $useHashAsFilename) {
         $useHashAsFilename = $this->config['use_hash_as_image_name'];
     }
     $contextPath = $this->config['base_path'] . '/' . $context;
     if (true === $useHashAsFilename) {
         $fileName = $this->generateHash();
     }
     $fileName .= '.' . $uploadedFile->guessExtension();
     if ($this->filesystem->exists($contextPath . '/' . $fileName) && true === $useHashAsFilename) {
         $this->upload($contextPath, $uploadedFile, $fileName, $useHashAsFilename);
     } elseif ($this->filesystem->exists($contextPath . '/' . $fileName) && false === $useHashAsFilename) {
         throw new IcrLogicException("File {$fileName} exists! Please choose another name!");
     }
     // Upload original file
     $this->filesystem->dumpFile($contextPath . '/' . $fileName, file_get_contents($uploadedFile->getRealPath()));
     foreach ($this->config['contexts'][$context] as $sizeName => $values) {
         // Process and manipulate
         $manipulator = $this->manipulatorFactory->create($values['operation']);
         $abstractImage = $this->openImageHandler->openImage($uploadedFile->getPathname());
         $image = $manipulator->manipulate($abstractImage, $values['width'], $values['height']);
         $path = $contextPath . '/' . $sizeName . '/';
         $this->filesystem->dumpFile($path . '/' . $fileName, $image);
     }
     return $fileName;
 }
 /**
  * Use Symfony components to guess the file extension.
  *
  * @return string
  *         File extension
  */
 public function getExtension()
 {
     if (!is_null($this->extension)) {
         return $this->extension;
     }
     return $this->extension = $this->info->getExtension() ?: $this->info->guessExtension();
 }
Exemple #10
0
 /**
  * @param File $file
  *
  * @return $this
  */
 public function setFile(File $file)
 {
     $this->file = $file;
     if ($file->getPathname()) {
         $this->filename = sha1(uniqid(mt_rand(), true)) . '.' . $file->guessExtension();
     }
     return $this;
 }
 /**
  * @ORM\PrePersist()
  * @ORM\PreUpdate()
  */
 public function preUpload()
 {
     if (null !== $this->file) {
         $filename = sha1(uniqid(mt_rand(), true));
         $this->path = $filename . '.' . $this->file->guessExtension();
         $this->name = $this->getFile()->getClientOriginalName();
     }
 }
 public function thumb(Request $request, $id)
 {
     $photo = Photo::findOrFail($id);
     $file = new File($photo->path);
     $photo->makeThumbnail();
     $headers = array('Content-Type: ' . $file->getMimeType());
     return response()->download($photo->path . '.' . $file->guessExtension(), $photo->name, $headers);
 }
 /**
  * @param \Exolnet\Image\Image                        $image
  * @param \Symfony\Component\HttpFoundation\File\File $file
  */
 public function updateImage(Image $image, File $file)
 {
     $this->destroy($image);
     $fileName = $image->getId() . '-' . Str::slug($file->getBasename()) . '.' . $file->guessExtension();
     $image->setFilename($fileName);
     $image->save();
     $this->store($image, $file);
 }
 /**
  * @param File $image
  * @param string $prefix
  * @param String $path
  * @return string
  */
 public function moveFile(File $image, $path, $prefix = '')
 {
     $extension = $image->guessExtension();
     $code = strtoupper($this->request->get('code'));
     $fileName = $code . '-' . $prefix . '.' . $extension;
     $image->move(public_path() . $path, $fileName);
     return $path . $fileName;
 }
 /**
  * Transform image to base 64
  * @param  string $path relative path to image from bundle directory
  * @return string       base64 encoded image
  */
 public function image64($path)
 {
     $file = new File($path, false);
     if (!$file->isFile() || 0 !== strpos($file->getMimeType(), 'image/')) {
         return;
     }
     $binary = file_get_contents($path);
     return sprintf('data:image/%s;base64,%s', $file->guessExtension(), base64_encode($binary));
 }
 /**
  * Copy a file into the /tmp directory
  * and returns a copy of this one
  *
  * @param  string $path
  * @return string
  */
 protected function getFileCopy($path)
 {
     $fs = new Filesystem();
     $tmpFile = new File($path);
     $tmpExtension = $tmpFile->guessExtension();
     $file = '/tmp/' . uniqid() . '.' . $tmpExtension;
     $fs->copy($path, $file);
     return $file;
 }
 /**
  * @inheritDoc
  */
 public function transform(File $file, ResourceAnnotationInterface $config)
 {
     /** @var  ResourceImage $config */
     //create copy with image extension instead of .tmp, required to save with Imagine
     $newName = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $file->getFilename() . '.' . $file->guessExtension();
     if (copy($file->getRealPath(), $newName)) {
         $newFile = new File($newName);
         return $this->imageResize($newFile, $config->maxWith, $config->maxHeight, $config->enlarge, $config->keepRatio);
     } else {
         return $file;
     }
 }
Exemple #18
0
 public function rotate($angle)
 {
     $this->removeThumbnail();
     $file = new File($this->path);
     $newfilePath = $this->path . 'new.' . $file->guessExtension();
     $image = Image::make($this->path);
     $image->rotate($angle);
     $image->save($newfilePath);
     unlink($this->path);
     rename($newfilePath, $this->path);
     $this->makeThumbnail();
 }
 /**
  * @param string $email
  * @return UploadedFile
  * @throws InvalidArgumentException
  */
 public function getFile($email)
 {
     if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
         throw new InvalidArgumentException();
     }
     $hash = md5(strtolower(trim($email)));
     $guzzle = new Client();
     $tempDirectory = sys_get_temp_dir();
     $guzzle->request("GET", "http://gravatar.com/avatar/" . $hash . "?d=404", [RequestOptions::SINK => $tempDirectory . '/' . $hash]);
     $file = new File($tempDirectory . '/' . $hash);
     $fileOriginalName = $hash . '.' . $file->guessExtension();
     $file = new UploadedFile($tempDirectory . '/' . $hash, $fileOriginalName, $file->getMimeType(), $file->getSize(), null, true);
     return $file;
 }
Exemple #20
0
 /**
  * @param resource|string|UploadedFile $resource
  * @return string Asset identifier
  */
 public function put($resource)
 {
     $tmpFileName = tempnam('/tmp', 'test_');
     if ($resource instanceof UploadedFile) {
         $pathinfo = pathinfo($tmpFileName);
         $resource->move($pathinfo['dirname'], $pathinfo['basename']);
     } else {
         file_put_contents($tmpFileName, $resource);
     }
     $checksum = sha1_file($tmpFileName);
     $file = new File($tmpFileName);
     $targetFileName = $checksum . '.' . $file->guessExtension();
     $target = $file->move($this->storageDirectory, $targetFileName);
     $filesystem = new Filesystem();
     $filesystem->chmod($target, 0777);
     return $targetFileName;
 }
Exemple #21
0
 /**
  * Instantiates the Resizer and receives the path to an image we're working with
  * @param mixed $file The file array provided by Laravel's Input::file('field_name') or a path to a file
  */
 function __construct($file)
 {
     if (!extension_loaded('gd')) {
         echo 'GD PHP library required.' . PHP_EOL;
         exit(1);
     }
     if (is_string($file)) {
         $file = new FileObj($file);
     }
     // Get the file extension
     $this->extension = $file->guessExtension();
     // Open up the file
     $this->image = $this->openImage($file);
     // Get width and height of our image
     $this->width = imagesx($this->image);
     $this->height = imagesy($this->image);
 }
Exemple #22
0
 /**
  * Instantiates the Resizer and receives the path to an image we're working with
  * @param mixed $file The file array provided by Laravel's Input::file('field_name') or a path to a file
  */
 function __construct($file)
 {
     if (!extension_loaded('gd')) {
         echo 'GD PHP library required.' . PHP_EOL;
         exit(1);
     }
     if (is_string($file)) {
         $file = new FileObj($file);
     }
     // Get the file extension
     $this->extension = $file->guessExtension();
     // Open up the file
     $this->image = $this->originalImage = $this->openImage($file);
     // Get width and height of our image
     $this->orientation = $this->getOrientation($file);
     // Get width and height of our image
     $this->width = $this->getWidth();
     $this->height = $this->getHeight();
     // Set default options
     $this->setOptions([]);
 }
 /**
  * Get the full target name for the uploaded file.
  *
  * @return string
  */
 protected function getTargetFileName()
 {
     if ($this->final) {
         return $this->fileName;
     }
     // Create a unique filename with a simple pattern
     $originalName = $this->file->getClientOriginalName();
     $extension = $this->file->guessExtension() ?: pathinfo($originalName, PATHINFO_EXTENSION);
     $pattern = $this->getTargetFileNamePattern();
     $fileName = sprintf($pattern, pathinfo($originalName, PATHINFO_FILENAME), $extension);
     $this->fullPath = $this->getTargetFileDirectory() . DIRECTORY_SEPARATOR . $fileName;
     $i = 1;
     while (file_exists($this->fullPath)) {
         $fileName = sprintf($pattern, pathinfo($originalName, PATHINFO_FILENAME) . "({$i})", $extension);
         $this->fullPath = $this->getTargetFileDirectory() . DIRECTORY_SEPARATOR . $fileName;
         $i++;
     }
     $this->app['logger.system']->debug("[BoltForms] Setting uploaded file '{$originalName}' to use the name '{$fileName}'.", array('event' => 'extensions'));
     $this->final = true;
     return $this->fileName = $fileName;
 }
Exemple #24
0
 /**
  * {@inheritdoc}
  */
 public function up(Schema $schema, QueryBag $queries)
 {
     //add attachment extend field
     self::addAvatarToUser($schema, $this->attachmentExtension);
     self::addOwnerToOroFile($schema);
     //save old avatars to new place
     $em = $this->container->get('doctrine.orm.entity_manager');
     $query = "SELECT id, image, createdAt FROM oro_user WHERE image != ''";
     $userImages = $em->getConnection()->executeQuery($query)->fetchAll(\PDO::FETCH_ASSOC);
     if (!empty($userImages)) {
         $maxId = (int) $em->getConnection()->executeQuery('SELECT MAX(id) FROM oro_attachment_file;')->fetchColumn();
         foreach ($userImages as $userData) {
             $filePath = $this->getUploadFileName($userData);
             // file doesn't exists or not readable
             if (false === $filePath || !is_readable($filePath)) {
                 $this->container->get('logger')->addAlert(sprintf('There\'s no image %s for user %d exists.', $userData['image'], $userData['id']));
                 continue;
             }
             try {
                 $this->container->get('oro_attachment.manager')->copyLocalFileToStorage($filePath, $userData['image']);
             } catch (\Exception $e) {
                 $this->container->get('logger')->addError(sprintf('File copy error: %s', $e->getMessage()));
             }
             $maxId++;
             $file = new SymfonyFile($filePath);
             $currentDate = new \DateTime();
             $query = sprintf('INSERT INTO oro_attachment_file
                 (id, filename, extension, mime_type, file_size, original_filename,
                  created_at, updated_at, owner_user_id)
                 values (%s, \'%s\', \'%s\', \'%s\', %s, \'%s\', \'%s\', \'%s\', %s);', $maxId, $file->getFileName(), $file->guessExtension(), $file->getMimeType(), $file->getSize(), $userData['image'], $currentDate->format('Y-m-d'), $currentDate->format('Y-m-d'), $userData['id']);
             $queries->addQuery($query);
             $query = sprintf('UPDATE oro_user set avatar_id = %d WHERE id = %d;', $maxId, $userData['id']);
             $queries->addQuery($query);
             unlink($filePath);
         }
     }
     //delete old avatars field
     $schema->getTable('oro_user')->dropColumn('image');
 }
 /**
  * Generate file path relative to contributed media directory
  *
  * @param Contribution $contribution
  * @param SplFileInfo  $file
  *
  * @return string
  */
 public function generateAbsolutePath(Contribution $contribution, File $file)
 {
     return $this->directory . DIRECTORY_SEPARATOR . $contribution->getAuthProvider() . DIRECTORY_SEPARATOR . $contribution->getIdentifier() . '.' . ($file->guessExtension() ?: $file->getExtension());
 }
Exemple #26
0
 /**
  * @param string|array $location
  * @param File         $file
  * @param array        $extraData
  * @param array        $options
  *
  * @return $this
  *
  * @throws ValidationException
  * @throws Exception
  */
 public function uploadBulk($location, File $file, $extraData = [], $options = [])
 {
     try {
         $this->call('POST', $this->buildUri($location, ['bulk' => true, 'upload' => true]), ['content' => base64_encode(file_get_contents($file->getRealPath())), 'type' => $this->getContentTypeByExtension($file->guessExtension()), 'filename' => $file->getFilename()] + $extraData, $options);
     } catch (Exception $e) {
         $this->throwSdkException($e);
     }
     return $this;
 }
 protected function createVideoRecord(File $video, array $attributes)
 {
     $meta = new Meta($video, $this->ffmpeg);
     $attributes = array_merge($attributes, ['width' => $meta->getWidth(), 'height' => $meta->getHeight(), 'orientation' => $meta->getOrientation(), 'mime_type' => $video->getMimeType(), 'extension' => $video->guessExtension()]);
     return $this->videos->create($attributes);
 }
Exemple #28
0
 /**
  * {@inheritDoc}
  */
 public function load(ObjectManager $manager)
 {
     // Cocktails
     $daiquiri = $this->getReference("daiquiri");
     $pinaColada = $this->getReference("pinaColada");
     $margarita = $this->getReference("margarita");
     $sexOnTheBeach = $this->getReference("sexOnTheBeach");
     $caipirinha = $this->getReference("caipirinha");
     $cosmopolitan = $this->getReference("cosmopolitan");
     $blueLagoon = $this->getReference("blueLagoon");
     $tequilaSunrise = $this->getReference("tequilaSunrise");
     $boraBora = $this->getReference("boraBora");
     $zombie = $this->getReference("zombie");
     $fs = new Filesystem();
     $path = $this->container->getParameter('kernel.root_dir') . '/../src/Automatiz/ApiBundle/DataFixtures/Images/';
     $fs->remove($this->container->getParameter('kernel.root_dir') . '/../web/uploads/cocktails_pictures');
     $fs->copy($path . "daiquirii.jpg", $path . "daiquirii-copy.jpg");
     $file = new File($path . "daiquirii-copy.jpg");
     $imageDir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/cocktails_pictures';
     $fileName = md5(uniqid()) . '.' . $file->guessExtension();
     $file->move($imageDir, $fileName);
     $image = new Image();
     $image->setFile($fileName);
     $image->setPath($imageDir);
     $image->setUrl("/uploads/cocktails_pictures/" . $fileName);
     $daiquiri->setImage($image);
     $manager->persist($daiquiri);
     $fs->copy($path . "pina-colada.jpg", $path . "pina-colada-copy.jpg");
     $file = new File($path . "pina-colada-copy.jpg");
     $imageDir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/cocktails_pictures';
     $fileName = md5(uniqid()) . '.' . $file->guessExtension();
     $file->move($imageDir, $fileName);
     $image = new Image();
     $image->setFile($fileName);
     $image->setPath($imageDir);
     $image->setUrl("/uploads/cocktails_pictures/" . $fileName);
     $pinaColada->setImage($image);
     $manager->persist($pinaColada);
     $fs->copy($path . "margarita.jpg", $path . "margarita-copy.jpg");
     $file = new File($path . "margarita-copy.jpg");
     $imageDir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/cocktails_pictures';
     $fileName = md5(uniqid()) . '.' . $file->guessExtension();
     $file->move($imageDir, $fileName);
     $image = new Image();
     $image->setFile($fileName);
     $image->setPath($imageDir);
     $image->setUrl("/uploads/cocktails_pictures/" . $fileName);
     $margarita->setImage($image);
     $manager->persist($margarita);
     $fs->copy($path . "sex-on-the-beach.jpg", $path . "sex-on-the-beach-copy.jpg");
     $file = new File($path . "sex-on-the-beach-copy.jpg");
     $imageDir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/cocktails_pictures';
     $fileName = md5(uniqid()) . '.' . $file->guessExtension();
     $file->move($imageDir, $fileName);
     $image = new Image();
     $image->setFile($fileName);
     $image->setPath($imageDir);
     $image->setUrl("/uploads/cocktails_pictures/" . $fileName);
     $sexOnTheBeach->setImage($image);
     $manager->persist($sexOnTheBeach);
     $fs->copy($path . "caipirinha.jpg", $path . "caipirinha-copy.jpg");
     $file = new File($path . "caipirinha-copy.jpg");
     $imageDir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/cocktails_pictures';
     $fileName = md5(uniqid()) . '.' . $file->guessExtension();
     $file->move($imageDir, $fileName);
     $image = new Image();
     $image->setFile($fileName);
     $image->setPath($imageDir);
     $image->setUrl("/uploads/cocktails_pictures/" . $fileName);
     $caipirinha->setImage($image);
     $manager->persist($caipirinha);
     $fs->copy($path . "cosmopolitan.jpg", $path . "cosmopolitan-copy.jpg");
     $file = new File($path . "cosmopolitan-copy.jpg");
     $imageDir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/cocktails_pictures';
     $fileName = md5(uniqid()) . '.' . $file->guessExtension();
     $file->move($imageDir, $fileName);
     $image = new Image();
     $image->setFile($fileName);
     $image->setPath($imageDir);
     $image->setUrl("/uploads/cocktails_pictures/" . $fileName);
     $cosmopolitan->setImage($image);
     $manager->persist($cosmopolitan);
     $fs->copy($path . "blue-lagoon.jpg", $path . "blue-lagoon-copy.jpg");
     $file = new File($path . "blue-lagoon-copy.jpg");
     $imageDir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/cocktails_pictures';
     $fileName = md5(uniqid()) . '.' . $file->guessExtension();
     $file->move($imageDir, $fileName);
     $image = new Image();
     $image->setFile($fileName);
     $image->setPath($imageDir);
     $image->setUrl("/uploads/cocktails_pictures/" . $fileName);
     $blueLagoon->setImage($image);
     $manager->persist($blueLagoon);
     $fs->copy($path . "tequila-sunrise.jpg", $path . "tequila-sunrise-copy.jpg");
     $file = new File($path . "tequila-sunrise-copy.jpg");
     $imageDir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/cocktails_pictures';
     $fileName = md5(uniqid()) . '.' . $file->guessExtension();
     $file->move($imageDir, $fileName);
     $image = new Image();
     $image->setFile($fileName);
     $image->setPath($imageDir);
     $image->setUrl("/uploads/cocktails_pictures/" . $fileName);
     $tequilaSunrise->setImage($image);
     $manager->persist($tequilaSunrise);
     $fs->copy($path . "bora-bora.jpg", $path . "bora-bora-copy.jpg");
     $file = new File($path . "bora-bora-copy.jpg");
     $imageDir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/cocktails_pictures';
     $fileName = md5(uniqid()) . '.' . $file->guessExtension();
     $file->move($imageDir, $fileName);
     $image = new Image();
     $image->setFile($fileName);
     $image->setPath($imageDir);
     $image->setUrl("/uploads/cocktails_pictures/" . $fileName);
     $boraBora->setImage($image);
     $manager->persist($boraBora);
     $fs->copy($path . "zombie.jpg", $path . "zombie-copy.jpg");
     $file = new File($path . "zombie-copy.jpg");
     $imageDir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/cocktails_pictures';
     $fileName = md5(uniqid()) . '.' . $file->guessExtension();
     $file->move($imageDir, $fileName);
     $image = new Image();
     $image->setFile($fileName);
     $image->setPath($imageDir);
     $image->setUrl("/uploads/cocktails_pictures/" . $fileName);
     $zombie->setImage($image);
     $manager->persist($zombie);
     $manager->flush();
 }
 /**
  * {@inheritdoc}
  */
 public function guessExtension()
 {
     return $this->extension ?: parent::guessExtension();
 }
 /**
  * @param File $file
  * @return string
  */
 public function generateReferenceName(File $file)
 {
     $name = sha1(uniqid() . rand(1, 9999));
     $extension = $file->guessExtension();
     return sprintf('%s.%s', $name, $extension);
 }