getMimeType example

public function on4xx(ExceptionEvent $event) {
    /** @var \Symfony\Component\HttpKernel\Exception\HttpExceptionInterface $exception */
    $exception = $event->getThrowable();
    $request = $event->getRequest();

    $format = $request->getRequestFormat();
    $content = ['message' => $exception->getMessage()];
    $encoded_content = $this->serializer->serialize($content$format);
    $headers = $exception->getHeaders();

    // Add the MIME type from the request to send back in the header.     $headers['Content-Type'] = $request->getMimeType($format);

    // If the exception is cacheable, generate a cacheable response.     if ($exception instanceof CacheableDependencyInterface) {
      $response = new CacheableResponse($encoded_content$exception->getStatusCode()$headers);
      $response->addCacheableDependency($exception);
    }
    else {
      $response = new Response($encoded_content$exception->getStatusCode()$headers);
    }

    $event->setResponse($response);
  }
    // enclosure per item. See: http://wikipedia.org/wiki/RSS_enclosure     foreach ($this->getEntitiesToView($items$langcode) as $file) {
      /** @var \Drupal\file\FileInterface $file */
      $entity->rss_elements[] = [
        'key' => 'enclosure',
        'attributes' => [
          // In RSS feeds, it is necessary to use absolute URLs. The 'url.site'           // cache context is already associated with RSS feed responses, so it           // does not need to be specified here.           'url' => $file->createFileUrl(FALSE),
          'length' => $file->getSize(),
          'type' => $file->getMimeType(),
        ],
      ];
    }
    return [];
  }

}

  protected function getSourceFiles(EntityReferenceFieldItemListInterface $items$langcode) {
    $source_files = [];
    // Because we can have the files grouped in a single media tag, we do a     // grouping in case the multiple file behavior is not 'tags'.     /** @var \Drupal\file\Entity\File $file */
    foreach ($this->getEntitiesToView($items$langcode) as $file) {
      if (static::mimeTypeApplies($file->getMimeType())) {
        $source_attributes = new Attribute();
        $source_attributes
          ->setAttribute('src', $file->createFileUrl())
          ->setAttribute('type', $file->getMimeType());
        if ($this->getSetting('multiple_file_display_type') === 'tags') {
          $source_files[] = [
            [
              'file' => $file,
              'source_attributes' => $source_attributes,
            ],
          ];
        }
public function prepare(Request $request)static
    {
        if ($this->isInformational() || $this->isEmpty()) {
            parent::prepare($request);

            $this->maxlen = 0;

            return $this;
        }

        if (!$this->headers->has('Content-Type')) {
            $this->headers->set('Content-Type', $this->file->getMimeType() ?: 'application/octet-stream');
        }

        parent::prepare($request);

        $this->offset = 0;
        $this->maxlen = -1;

        if (false === $fileSize = $this->file->getSize()) {
            return $this;
        }
        $this->headers->remove('Transfer-Encoding');
        


    // We do not throw a     // \Symfony\Component\Routing\Exception\ResourceNotFoundException here     // because we don't want to return a 404 status code, but rather a 406.     $available_formats = static::getAvailableFormats($collection);
    $not_acceptable = new NotAcceptableHttpException("No route found for the specified format $format. Supported formats: " . implode(', ', $available_formats) . '.');
    if ($available_formats) {
      $links = [];
      foreach ($available_formats as $available_format) {
        $url = Url::fromUri($request->getUri()['query' => ['_format' => $available_format]])->toString(TRUE)->getGeneratedUrl();
        $content_type = $request->getMimeType($available_format);
        $links[] = "<$url>; rel=\"alternate\"; type=\"$content_type\"";
      }
      $not_acceptable->setHeaders(['Link' => implode(', ', $links)]);
    }
    throw $not_acceptable;
  }

  /** * Determines the default request format. * * By default, use 'html' as the default format. But when there's only a * single route match, and that route specifies a '_format' requirement * listing a single format, then use that as the default format. Also, if * there are multiple routes which all require the same single format then * use it. * * @param \Symfony\Component\Routing\RouteCollection $collection * The route collection to filter. * * @return string * The default format. */
$imageSliderStruct = $slot->getData();

        static::assertInstanceOf(ImageSliderStruct::class$imageSliderStruct);

        $imageSliderItems = $imageSliderStruct->getSliderItems() ?? [];
        static::assertCount(2, $imageSliderItems);

        $firstSliderItem = $imageSliderItems[0];
        $firstSliderItemMedia = $firstSliderItem->getMedia();
        static::assertInstanceOf(MediaEntity::class$firstSliderItemMedia);
        static::assertEquals('animated', $firstSliderItemMedia->getFileName());
        static::assertEquals('image/gif', $firstSliderItemMedia->getMimeType());
        static::assertEquals('gif', $firstSliderItemMedia->getFileExtension());

        $secondSliderItem = $imageSliderItems[1];
        $secondSliderItemMedia = $secondSliderItem->getMedia();
        static::assertInstanceOf(MediaEntity::class$secondSliderItemMedia);
        static::assertEquals('shopware', $secondSliderItemMedia->getFileName());
        static::assertEquals('image/jpeg', $secondSliderItemMedia->getMimeType());
        static::assertEquals('jpg', $secondSliderItemMedia->getFileExtension());
    }

    public function testEnrichWithCoverIdButWithoutCoverMedia(): void
    {
->setParameter('{{ file }}', $this->formatValue($path))
                    ->setParameter('{{ extension }}', $this->formatValue($fileExtension))
                    ->setParameter('{{ extensions }}', $this->formatValues($normalizedExtensions))
                    ->setParameter('{{ name }}', $this->formatValue($basename))
                    ->setCode(File::INVALID_EXTENSION_ERROR)
                    ->addViolation();
            }
        }

        if ($mimeTypes) {
            if ($value instanceof FileObject) {
                $mime = $value->getMimeType();
            } elseif (isset($mimeTypesHelper) || class_exists(MimeTypes::class)) {
                $mime = ($mimeTypesHelper ?? MimeTypes::getDefault())->guessMimeType($path);
            } elseif (!class_exists(FileObject::class)) {
                throw new LogicException('You cannot validate the mime-type of files as the Mime component is not installed. Try running "composer require symfony/mime".');
            } else {
                $mime = (new FileObject($value))->getMimeType();
            }

            foreach ($mimeTypes as $mimeType) {
                if ($mimeType === $mime) {
                    return;
                }
$this->setContentType($default_format);
    }

    // Only use the requested content type if it's not 'html'. This allows     // still falling back to the default for things like views preview.     $request_content_type = $this->view->getRequest()->getRequestFormat();

    if ($request_content_type !== 'html') {
      $this->setContentType($request_content_type);
    }

    $this->setMimeType($this->view->getRequest()->getMimeType($this->getContentType()));
  }

  /** * {@inheritdoc} */
  public function getType() {
    return 'data';
  }

  /** * {@inheritdoc} */
if ($this->isInformational() || $this->isEmpty()) {
            $this->setContent(null);
            $headers->remove('Content-Type');
            $headers->remove('Content-Length');
            // prevent PHP from sending the Content-Type header based on default_mimetype             ini_set('default_mimetype', '');
        } else {
            // Content-type based on the Request             if (!$headers->has('Content-Type')) {
                $format = $request->getRequestFormat(null);
                if (null !== $format && $mimeType = $request->getMimeType($format)) {
                    $headers->set('Content-Type', $mimeType);
                }
            }

            // Fix Content-Type             $charset = $this->charset ?: 'UTF-8';
            if (!$headers->has('Content-Type')) {
                $headers->set('Content-Type', 'text/html; charset='.$charset);
            } elseif (0 === stripos($headers->get('Content-Type') ?? '', 'text/') && false === stripos($headers->get('Content-Type') ?? '', 'charset')) {
                // add the charset                 $headers->set('Content-Type', $headers->get('Content-Type').'; charset='.$charset);
            }
$response->prepare($request);

        $this->assertSame(BinaryFileResponse::HTTP_NOT_MODIFIED, $response->getStatusCode());
        $this->assertFalse($response->headers->has('Content-Type'));
    }

    public function testContentTypeIsCorrectlyDetected()
    {
        $file = new File(__DIR__.'/File/Fixtures/test.gif');

        try {
            $file->getMimeType();
        } catch (\LogicException $e) {
            $this->markTestSkipped('Guessing the mime type is not possible');
        }

        $response = new BinaryFileResponse($file);

        $request = Request::create('/');
        $response->prepare($request);

        $this->assertSame(200, $response->getStatusCode());
        $this->assertSame('image/gif', $response->headers->get('Content-Type'));
    }

  public function testCreateImageFromScratch(int $type): void {
    // Build an image from scratch.     $image = $this->imageFactory->get();
    $image->createNew(50, 20, image_type_to_extension($type, FALSE), '#ffff00');
    $file = 'from_null' . image_type_to_extension($type);
    $file_path = $this->directory . '/' . $file;
    $this->assertSame(50, $image->getWidth());
    $this->assertSame(20, $image->getHeight());
    $this->assertSame(image_type_to_mime_type($type)$image->getMimeType());
    $this->assertTrue($image->save($file_path), "Image '$file' should have been saved successfully, but it has not.");

    // Reload and check saved image.     $image_reloaded = $this->imageFactory->get($file_path);
    $this->assertTrue($image_reloaded->isValid());
    $this->assertSame(50, $image_reloaded->getWidth());
    $this->assertSame(20, $image_reloaded->getHeight());
    $this->assertSame(image_type_to_mime_type($type)$image_reloaded->getMimeType());
    if ($image_reloaded->getToolkit()->getType() == IMAGETYPE_GIF) {
      $this->assertSame('#ffff00', $image_reloaded->getToolkit()->getTransparentColor(), "Image '$file' after reload should have color channel set to #ffff00, but it has not.");
    }
    

  protected function assertEntity($id$name$uri$mime$size$created$changed$uid) {
    /** @var \Drupal\file\FileInterface $file */
    $file = File::load($id);
    $this->assertInstanceOf(FileInterface::class$file);
    $this->assertSame($name$file->getFilename());
    $this->assertSame($uri$file->getFileUri());
    $this->assertFileExists($uri);
    $this->assertSame($mime$file->getMimeType());
    $this->assertSame($size$file->getSize());
    // isPermanent(), isTemporary(), etc. are determined by the status column.     $this->assertTrue($file->isPermanent());
    $this->assertSame($created$file->getCreatedTime());
    $this->assertSame($changed$file->getChangedTime());
    $this->assertSame($uid$file->getOwnerId());
  }

}
if ($this->isInformational() || $this->isEmpty()) {
            $this->setContent(null);
            $headers->remove('Content-Type');
            $headers->remove('Content-Length');
            // prevent PHP from sending the Content-Type header based on default_mimetype             ini_set('default_mimetype', '');
        } else {
            // Content-type based on the Request             if (!$headers->has('Content-Type')) {
                $format = $request->getRequestFormat(null);
                if (null !== $format && $mimeType = $request->getMimeType($format)) {
                    $headers->set('Content-Type', $mimeType);
                }
            }

            // Fix Content-Type             $charset = $this->charset ?: 'UTF-8';
            if (!$headers->has('Content-Type')) {
                $headers->set('Content-Type', 'text/html; charset='.$charset);
            } elseif (0 === stripos($headers->get('Content-Type') ?? '', 'text/') && false === stripos($headers->get('Content-Type') ?? '', 'charset')) {
                // add the charset                 $headers->set('Content-Type', $headers->get('Content-Type').'; charset='.$charset);
            }

        $file = new UploadedFile(
            __DIR__.'/Fixtures/test.gif',
            'original.gif',
            null,
            \UPLOAD_ERR_OK
        );

        $this->assertEquals('application/octet-stream', $file->getClientMimeType());

        if (\extension_loaded('fileinfo')) {
            $this->assertEquals('image/gif', $file->getMimeType());
        }
    }

    public function testFileUploadsWithUnknownMimeType()
    {
        $file = new UploadedFile(
            __DIR__.'/Fixtures/.unknownextension',
            'original.gif',
            null,
            \UPLOAD_ERR_OK
        );

        
/** * {@inheritdoc} */
  public function getFileSize() {
    return $this->fileSize;
  }

  /** * {@inheritdoc} */
  public function getMimeType() {
    return $this->getToolkit()->getMimeType();
  }

  /** * {@inheritdoc} */
  public function getSource() {
    return $this->source;
  }

  /** * {@inheritdoc} */
Home | Imprint | This part of the site doesn't use cookies.