guessMimeType example

$this->service = $this->container->get($this->drupalProxyOriginalServiceId);
            }

            return $this->service;
        }

        /** * {@inheritdoc} */
        public function guessMimeType($path): ?string
        {
            return $this->lazyLoadItself()->guessMimeType($path);
        }

        /** * {@inheritdoc} */
        public function setMapping(?array $mapping = NULL)
        {
            return $this->lazyLoadItself()->setMapping($mapping);
        }

        /** * {@inheritdoc} */
'foo.file_test_1' => 'madeup/file_test_1',
      'foo.file_test_2' => 'madeup/file_test_2',
      'foo.doc' => 'madeup/doc',
      'test.ogg' => 'audio/ogg',
    ];

    $guesser = $this->container->get('file.mime_type.guesser');
    // Test using default mappings.     foreach ($test_case as $input => $expected) {
      // Test stream [URI].       foreach ($prefixes as $prefix) {
        $output = $guesser->guessMimeType($prefix . $input);
        $this->assertSame($expected$output);
      }

      // Test normal path equivalent       $output = $guesser->guessMimeType($input);
      $this->assertSame($expected$output);
    }

    // Now test the extension guesser by passing in a custom mapping.     $mapping = [
      'mimetypes' => [
        
abstract protected function getGuesser(): MimeTypeGuesserInterface;

    public function testGuessWithLeadingDash()
    {
        if (!$this->getGuesser()->isGuesserSupported()) {
            $this->markTestSkipped('Guesser is not supported');
        }

        $cwd = getcwd();
        chdir(__DIR__.'/Fixtures/mimetypes');
        try {
            $this->assertEquals('image/gif', $this->getGuesser()->guessMimeType('-test'));
        } finally {
            chdir($cwd);
        }
    }

    public function testGuessImageWithoutExtension()
    {
        if (!$this->getGuesser()->isGuesserSupported()) {
            $this->markTestSkipped('Guesser is not supported');
        }

        
// A file URI may already have a trailing slash or look like "public://".     if (substr($destination, -1) != '/') {
      $destination .= '/';
    }

    // Call an event to sanitize the filename and to attempt to address security     // issues caused by common server setups.     $event = new FileUploadSanitizeNameEvent($originalName$extensions);
    $this->eventDispatcher->dispatch($event);
    $filename = $event->getFilename();

    $mimeType = $this->mimeTypeGuesser->guessMimeType($filename);
    $destinationFilename = $this->fileSystem->getDestinationFilename($destination . $filename$replace);
    if ($destinationFilename === FALSE) {
      throw new FileExistsException(sprintf('Destination file "%s" exists', $destinationFilename));
    }

    $file = File::create([
      'uid' => $this->currentUser->id(),
      'status' => 0,
      'uri' => $uploadedFile->getRealPath(),
    ]);

    
$contentLength += 0 <= $contentLength ? substr($h, 16) : 0;
                    } elseif (\is_string($h) && 0 === stripos($h, 'Content-Encoding: ')) {
                        $contentLength = -1;
                    }
                }

                if (!$hasContentLength) {
                    $contentLength = -1;
                }
                if (null === $contentType && 'plainfile' === ($m['wrapper_type'] ?? null) && isset($m['uri'])) {
                    $mimeTypes = class_exists(MimeTypes::class) ? MimeTypes::getDefault() : false;
                    $contentType = $mimeTypes ? $mimeTypes->guessMimeType($m['uri']) : null;
                }
                $contentType ??= 'application/octet-stream';

                $part .= "Content-Disposition: form-data; name=\"{$k}\"; filename=\"{$filename}\"\r\n";
                $part .= "Content-Type: {$contentType}\r\n\r\n";

                $contentLength += 0 <= $contentLength ? \strlen($part) : 0;
                $body[$i] = [$k$part$v];
            }

            $body[++$i] = ['', "\r\n--{$boundary}--\r\n", null];

            


    /** * Gets the mime type of the object. Defaults to application/octet-stream. */
    private function getMimeType(\SplFileInfo $object): string
    {
        if ($object instanceof File) {
            return $object->getMimeType();
        }

        return $this->mimeTypeGuesser?->guessMimeType($object->getPathname()) ?: 'application/octet-stream';
    }

    /** * Returns the \SplFileObject instance associated with the given \SplFileInfo instance. */
    private function extractSplFileObject(\SplFileInfo $object): \SplFileObject
    {
        if ($object instanceof \SplFileObject) {
            return $object;
        }

        

    public function getMimeType(): ?string
    {
        if (!class_exists(MimeTypes::class)) {
            throw new \LogicException('You cannot guess the mime type as the Mime component is not installed. Try running "composer require symfony/mime".');
        }

        return MimeTypes::getDefault()->guessMimeType($this->getPathname());
    }

    /** * Moves the file to a new location. * * @throws FileException if the target file could not be created */
    public function move(string $directory, string $name = null): self
    {
        $target = $this->getTargetFile($directory$name);

        
// Lock based on the prepared file URI.     $lock_id = $this->generateLockIdFromFileUri($file_uri);

    if (!$this->lock->acquire($lock_id)) {
      throw new HttpException(503, sprintf('File "%s" is already locked for writing', $file_uri), NULL, ['Retry-After' => 1]);
    }

    // Begin building file entity.     $file = File::create([]);
    $file->setOwnerId($this->currentUser->id());
    $file->setFilename($prepared_filename);
    $file->setMimeType($this->mimeTypeGuesser->guessMimeType($prepared_filename));
    $file->setFileUri($temp_file_path);
    // Set the size. This is done in File::preSave() but we validate the file     // before it is saved.     $file->setSize(@filesize($temp_file_path));

    // Validate the file against field-level validators first while the file is     // still a temporary file. Validation is split up in 2 steps to be the same     // as in \Drupal\file\Upload\FileUploadHandler::handleFileUpload().     // For backwards compatibility this part is copied from ::validate() to     // leave that method behavior unchanged.     // @todo Improve this with a file uploader service in
if ($real_path !== FALSE) {
        $path = $real_path;
      }
    }

    if ($this->sortedGuessers === NULL) {
      // Sort is not triggered yet.       $this->sortedGuessers = $this->sortGuessers();
    }

    foreach ($this->sortedGuessers as $guesser) {
      $mime_type = $guesser->guessMimeType($path);
      if ($mime_type !== NULL) {
        return $mime_type;
      }
    }

    return NULL;
  }

  /** * Appends a MIME type guesser to the guessers chain. * * @param \Symfony\Component\Mime\MimeTypeGuesserInterface $guesser * The guesser to be appended. * @param int $priority * The priority of the guesser being added. * * @return $this */
// Lock based on the prepared file URI.     $lock_id = $this->generateLockIdFromFileUri($file_uri);

    if (!$this->lock->acquire($lock_id)) {
      throw new HttpException(503, sprintf('File "%s" is already locked for writing.', $file_uri), NULL, ['Retry-After' => 1]);
    }

    // Begin building file entity.     $file = File::create([]);
    $file->setOwnerId($this->currentUser->id());
    $file->setFilename($prepared_filename);
    $file->setMimeType($this->mimeTypeGuesser->guessMimeType($prepared_filename));

    $file->setFileUri($file_uri);
    $file->setSize(@filesize($temp_file_path));

    $violations = $this->validate($file$validators);
    if ($violations->count() > 0) {
      throw new UnprocessableEntityHttpException($violations->__toString());
    }

    try {
      $this->fileSystem->move($temp_file_path$file_uri, FileSystemInterface::EXISTS_ERROR);
    }


    /** * Gets the mime type of the object. Defaults to application/octet-stream. */
    private function getMimeType(\SplFileInfo $object): string
    {
        if ($object instanceof File) {
            return $object->getMimeType();
        }

        return $this->mimeTypeGuesser?->guessMimeType($object->getPathname()) ?: 'application/octet-stream';
    }

    /** * Returns the \SplFileObject instance associated with the given \SplFileInfo instance. */
    private function extractSplFileObject(\SplFileInfo $object): \SplFileObject
    {
        if ($object instanceof \SplFileObject) {
            return $object;
        }

        

    public function guessMimeType(string $path): ?string
    {
        foreach ($this->guessers as $guesser) {
            if (!$guesser->isGuesserSupported()) {
                continue;
            }

            if (null !== $mimeType = $guesser->guessMimeType($path)) {
                return $mimeType;
            }
        }

        if (!$this->isGuesserSupported()) {
            throw new LogicException('Unable to guess the MIME type as no guessers are available (have you enabled the php_fileinfo extension?).');
        }

        return null;
    }

    

  public static function isApplicable(FieldDefinitionInterface $field_definition) {
    if (!parent::isApplicable($field_definition)) {
      return FALSE;
    }
    /** @var \Symfony\Component\Mime\MimeTypeGuesserInterface $extension_mime_type_guesser */
    $extension_mime_type_guesser = \Drupal::service('file.mime_type.guesser.extension');
    $extension_list = array_filter(preg_split('/\s+/', $field_definition->getSetting('file_extensions')));

    foreach ($extension_list as $extension) {
      $mime_type = $extension_mime_type_guesser->guessMimeType('fakedFile.' . $extension);
      if (static::mimeTypeApplies($mime_type)) {
        return TRUE;
      }
    }
    return FALSE;
  }

  /** * {@inheritdoc} */
  public function settingsSummary() {
    
// Lock based on the prepared file URI.     $lock_id = $this->generateLockIdFromFileUri($file_uri);

    if (!$this->lock->acquire($lock_id)) {
      throw new HttpException(503, sprintf('File "%s" is already locked for writing.', $file_uri), NULL, ['Retry-After' => 1]);
    }

    // Begin building file entity.     $file = File::create([]);
    $file->setOwnerId($owner->id());
    $file->setFilename($prepared_filename);
    $file->setMimeType($this->mimeTypeGuesser->guessMimeType($prepared_filename));
    $file->setFileUri($temp_file_path);
    // Set the size. This is done in File::preSave() but we validate the file     // before it is saved.     $file->setSize(@filesize($temp_file_path));

    // Validate the file against field-level validators first while the file is     // still a temporary file. Validation is split up in 2 steps to be the same     // as in \Drupal\file\Upload\FileUploadHandler::handleFileUpload().     // For backwards compatibility this part is copied from ::validate() to     // leave that method behavior unchanged.     // @todo Improve this with a file uploader service in
try {
        $file_system->move($tmp_file$destination);
      }
      catch (FileException $e) {
        // Ignore failed move.       }
      if ($path = $random->image($file_system->realpath($destination)$min_resolution$max_resolution)) {
        $image = File::create();
        $image->setFileUri($path);
        $image->setOwnerId(\Drupal::currentUser()->id());
        $guesser = \Drupal::service('file.mime_type.guesser');
        $image->setMimeType($guesser->guessMimeType($path));
        $image->setFileName($file_system->basename($path));
        $destination_dir = static::doGetUploadLocation($settings);
        $file_system->prepareDirectory($destination_dir, FileSystemInterface::CREATE_DIRECTORY);
        $destination = $destination_dir . '/' . basename($path);
        $file = \Drupal::service('file.repository')->move($image$destination);
        $images[$extension][$min_resolution][$max_resolution][$file->id()] = $file;
      }
      else {
        return [];
      }
    }
    
Home | Imprint | This part of the site doesn't use cookies.