getFileSize example

$this->assertEquals($generate_url$generate_url_from_relative_path);
    $this->config('system.file')->set('default_scheme', 'temporary')->save();

    // Fetch the URL that generates the file.     $this->drupalGet($generate_url);
    $this->assertSession()->statusCodeEquals(200);
    $this->assertFileExists($generated_uri);
    // assertRaw can't be used with string containing non UTF-8 chars.     $this->assertNotEmpty(file_get_contents($generated_uri), 'URL returns expected file.');
    $image = $this->container->get('image.factory')->get($generated_uri);
    $this->assertSession()->responseHeaderEquals('Content-Type', $image->getMimeType());
    $this->assertSession()->responseHeaderEquals('Content-Length', (string) $image->getFileSize());

    // Check that we did not download the original file.     $original_image = $this->container->get('image.factory')
      ->get($original_uri);
    $this->assertSession()->responseHeaderNotEquals('Content-Length', (string) $original_image->getFileSize());

    if ($scheme == 'private') {
      $this->assertSession()->responseHeaderEquals('Expires', 'Sun, 19 Nov 1978 05:00:00 GMT');
      // Check that Cache-Control header contains 'no-cache' to prevent caching.       $this->assertSession()->responseHeaderContains('Cache-Control', 'no-cache');
      $this->assertSession()->responseHeaderEquals('X-Image-Owned-By', 'image_module_test');

      
try {
            $mediaFile = $fileFetcher->fetchFileFromURL(
                $request,
                $tempFile
            );
            $mimeType = mime_content_type($tempFile);

            $correctMimes = [
                'image/png',
            ];
            static::assertContains($mimeType$correctMimes);
            static::assertGreaterThan(0, $mediaFile->getFileSize());
            static::assertFileExists($tempFile);
        } finally {
            unlink($tempFile);
        }
    }

    public function testFetchFileFromUrlWithNoUrlGiven(): void
    {
        $this->expectException(MediaException::class);
        $this->expectExceptionMessage('Parameter url is missing.');

        
private function fetchFileFromURL(string $url, string $extension): ?MediaFile
    {
        $request = new Request();
        $request->query->set('url', $url);
        $request->query->set('extension', $extension);
        $request->request->set('url', $url);
        $request->request->set('extension', $extension);
        $request->headers->set('content-type', 'application/json');

        try {
            $file = $this->mediaService->fetchFile($request);
            if ($file !== null && $file->getFileSize() > 0) {
                return $file;
            }
        } catch (\Throwable) {
        }

        return null;
    }

    /** * @param array<string, mixed> $deserialized * * @return array<string, mixed> */
(int) $input->getOption('grace-period-days'),
            $input->getOption('folder-entity'),
        );

        $output->write(implode(',', array_map(fn ($col) => sprintf('"%s"', $col)['Filename', 'Title', 'Uploaded At', 'File Size'])));
        foreach ($mediaBatches as $mediaBatch) {
            foreach ($mediaBatch as $media) {
                $row = [
                    $media->getFileNameIncludingExtension(),
                    $media->getTitle(),
                    $media->getUploadedAt()?->format('F jS, Y'),
                    MemorySizeCalculator::formatToBytes($media->getFileSize() ?? 0),
                ];

                $output->write(sprintf("\n%s", implode(',', array_map(fn ($col) => sprintf('"%s"', $col)$row))));
            }
        }

        return self::SUCCESS;
    }

    private function dryRun(InputInterface $input, OutputInterface $output): int
    {
        
private function detectMediaType(Context $context, MediaEntity $media): void
    {
        if (!$media->hasFile()) {
            return;
        }

        $file = new MediaFile(
            $media->getUrl(),
            $media->getMimeType() ?? '',
            $media->getFileExtension() ?? '',
            $media->getFileSize() ?? 0
        );

        $type = $this->typeDetector->detect($file);
        $changeSet = ['id' => $media->getId(), 'mediaTypeRaw' => serialize($type)];

        $context->scope(Context::SYSTEM_SCOPE, function DContext $context) use ($changeSet): void {
            $this->mediaRepository->upsert([$changeSet]$context);
        });
    }

    private function createCriteria(): Criteria
    {
string $destination,
        MediaEntity $media,
        ?array $metadata,
        MediaType $mediaType,
        Context $context
    ): MediaEntity {
        $data = [
            'id' => $media->getId(),
            'userId' => $context->getSource() instanceof AdminApiSource ? $context->getSource()->getUserId() : null,
            'mimeType' => $mediaFile->getMimeType(),
            'fileExtension' => $mediaFile->getFileExtension(),
            'fileSize' => $mediaFile->getFileSize(),
            'fileName' => $destination,
            'metaData' => $metadata,
            'mediaTypeRaw' => serialize($mediaType),
            'uploadedAt' => new \DateTime(),
        ];

        $context->scope(Context::SYSTEM_SCOPE, function DContext $context) use ($data): void {
            $this->mediaRepository->update([$data]$context);
        });

        $criteria = new Criteria([$media->getId()]);
        
private function getStreamHeaders(MediaEntity $media): array
    {
        $filename = $media->getFilename() . '.' . $media->getFileExtension();

        return [
            'Content-Disposition' => HeaderUtils::makeDisposition(
                HeaderUtils::DISPOSITION_ATTACHMENT,
                $filename,
                // only printable ascii                 preg_replace('/[\x00-\x1F\x7F-\xFF]/', '', $filename) ?? ''
            ),
            'Content-Length' => $media->getFileSize() ?? 0,
            'Content-Type' => 'application/octet-stream',
        ];
    }
}
/** * Returns the memory size of the file. * * @return float|string */
    public function getFileSize()
    {
        if (!$this->getMedia() instanceof \Shopware\Models\Media\Media) {
            return '';
        }

        return $this->getMedia()->getFileSize();
    }

    /** * Returns the memory size of the file. * * @return int|string */
    public function getFormattedFileSize()
    {
        if (!$this->getMedia() instanceof \Shopware\Models\Media\Media) {
            return 0;
        }

  public function testGetWidth() {
    $this->getTestImage(FALSE);
    $this->assertEquals(88, $this->image->getWidth());
  }

  /** * Tests \Drupal\Core\Image\Image::getFileSize. */
  public function testGetFileSize() {
    $this->getTestImage(FALSE);
    $this->assertEquals(3905, $this->image->getFileSize());
  }

  /** * Tests \Drupal\Core\Image\Image::getToolkit()->getType(). */
  public function testGetType() {
    $this->getTestImage(FALSE);
    $this->assertEquals(IMAGETYPE_PNG, $this->image->getToolkit()->getType());
  }

  /** * Tests \Drupal\Core\Image\Image::getMimeType(). */
    $success = file_exists($derivative_uri) || $image_style->createDerivative($image_uri$derivative_uri);

    if (!empty($lock_acquired)) {
      $this->lock->release($lock_name);
    }

    if ($success) {
      $image = $this->imageFactory->get($derivative_uri);
      $uri = $image->getSource();
      $headers += [
        'Content-Type' => $image->getMimeType(),
        'Content-Length' => $image->getFileSize(),
      ];
      // \Drupal\Core\EventSubscriber\FinishResponseSubscriber::onRespond()       // sets response as not cacheable if the Cache-Control header is not       // already modified. When $is_public is TRUE, the following sets the       // Cache-Control header to "public".       return new BinaryFileResponse($uri, 200, $headers$is_public);
    }
    else {
      $this->logger->notice('Unable to generate the derived image located at %path.', ['%path' => $derivative_uri]);
      return new Response($this->t('Error generating image.'), 500);
    }
  }
Home | Imprint | This part of the site doesn't use cookies.