readStream example

$fs = new Filesystem(new MemoryFilesystemAdapter()['public_url' => 'http://example.com'], null, null, $generator);
        $prefix = new PrefixFilesystem($fs, 'foo');

        $prefix->write('foo.txt', 'bla');
        static::assertTrue($prefix->fileExists('foo.txt'));
        static::assertTrue($prefix->has('foo.txt'));
        static::assertFalse($prefix->directoryExists('foo.txt'));
        static::assertTrue($fs->has('foo/foo.txt'));
        static::assertFalse($fs->directoryExists('foo/foo.txt'));

        static::assertSame('bla', $prefix->read('foo.txt'));
        static::assertSame('bla', stream_get_contents($prefix->readStream('foo.txt')));
        static::assertSame('text/plain', $prefix->mimeType('foo.txt'));
        static::assertSame(3, $prefix->fileSize('foo.txt'));
        static::assertSame(Visibility::PUBLIC$prefix->visibility('foo.txt'));
        $prefix->setVisibility('foo.txt', Visibility::PRIVATE);
        static::assertSame(Visibility::PRIVATE$prefix->visibility('foo.txt'));
        static::assertEqualsWithDelta($prefix->lastModified('foo.txt')time(), 2);

        static::assertSame('http://example.com/foo/foo.txt', $prefix->publicUrl('foo.txt'));
        static::assertSame('128ecf542a35ac5270a87dc740918404', $prefix->checksum('foo.txt'));
        static::assertSame('http://example.com/temporary-url', $prefix->temporaryUrl('foo.txt', new \DateTime('+1 hour')));

        
$this->Front()->Plugins()->ViewRenderer()->setNoRender();

        $response = $this->Response();
        $response->headers->set('content-type', $mimeType);
        $response->headers->set('content-disposition', sprintf('attachment; filename="%s"', basename($path)));
        $response->headers->set('content-length', $meta['size']);
        $response->headers->set('content-transfer-encoding', 'binary');
        $response->sendHeaders();
        $response->sendResponse();

        $upstream = $filesystem->readStream($path);
        if (!\is_resource($upstream)) {
            throw new RuntimeException(sprintf('Could not open file from: %s', $path));
        }
        $downstream = fopen('php://output', 'wb');
        if (!\is_resource($downstream)) {
            throw new RuntimeException('Could not open temporary stream');
        }

        ob_end_clean();

        while (!feof($upstream)) {
            
return $this->files[$path]->read();
    }

    public function readStream(string $path)
    {
        $path = $this->preparePath($path);

        if (!\array_key_exists($path$this->files)) {
            throw UnableToReadFile::fromLocation($path, 'file does not exist');
        }

        return $this->files[$path]->readStream();
    }

    public function delete(string $path): void
    {
        unset($this->files[$this->preparePath($path)]);
    }

    public function deleteDirectory(string $prefix): void
    {
        $prefix = $this->preparePath($prefix);
        $prefix = rtrim($prefix, '/') . '/';

        
public function testWriteStream(): void
    {
        $fs = new Filesystem(new MemoryFilesystemAdapter());
        $tmpFile = sys_get_temp_dir() . '/' . uniqid('test', true);
        file_put_contents($tmpFile, 'test');

        $fs->writeStream('a.txt', fopen($tmpFile, 'rb'));

        static::assertTrue($fs->fileExists('a.txt'));
        static::assertSame('test', $fs->read('a.txt'));
        static::assertSame('test', stream_get_contents($fs->readStream('a.txt')));

        unlink($tmpFile);
    }

    public function testReadNotExistingFile(): void
    {
        $fs = new Filesystem(new MemoryFilesystemAdapter());
        static::expectException(UnableToReadFile::class);
        $fs->read('foo');
    }

    
return $this->filesystem->read($this->prefix . $path);
    }

    /** * {@inheritdoc} */
    public function readStream($path)
    {
        $this->checkPath($path);

        return $this->filesystem->readStream($this->prefix . $path);
    }

    /** * {@inheritdoc} */
    public function listContents($directory = '', $recursive = false)
    {
        $this->checkPath($directory);

        return array_map(
            function D$info) {
                
// file already exists         if ($toFileSystem->has($path)) {
            ++$this->counter['skipped'];

            return;
        }

        // move file to new filesystem and remove the old one         if ($fromFilesystem->has($path)) {
            ++$this->counter['moved'];
            $success = $this->writeStream($toFileSystem$path$fromFilesystem->readStream($path));
            if ($success) {
                $fromFilesystem->delete($path);
            }

            return;
        }

        throw new RuntimeException('File not found: ' . $path);
    }

    /** * @param string $path * @param resource $contents * * @return bool */
if (!$invalidLogId) {
            return [];
        }

        $logEntity = $this->getLogEntity($invalidLogId);
        $config = Config::fromLog($logEntity);
        $reader = new CsvReader();
        $filesystem = $this->getContainer()->get('shopware.filesystem.private');

        /** @var ImportExportFileEntity $file */
        $file = $logEntity->getFile();
        $resource = $filesystem->readStream($file->getPath());
        $log = $reader->read($config$resource, 0);

        return $log instanceof \Traversable ? iterator_to_array($log) : [];
    }

    /** * @param array<array<string, string>> $customFields */
    protected function createCustomField(array $customFields, string $entityName): void
    {
        $repo = $this->getContainer()->get('custom_field_set.repository');

        
$headers = [
            'Content-Disposition' => HeaderUtils::makeDisposition(
                'attachment',
                $originalName,
                // only printable ascii                 (string) preg_replace('/[\x00-\x1F\x7F-\xFF]/', '', $originalName)
            ),
            'Content-Length' => $this->filesystem->fileSize($entity->getPath()),
            'Content-Type' => 'application/octet-stream',
        ];
        $stream = $this->filesystem->readStream($entity->getPath());
        if (!\is_resource($stream)) {
            throw ImportExportException::fileNotFound($fileId);
        }

        return new StreamedResponse(function D) use ($stream): void {
            fpassthru($stream);
        }, Response::HTTP_OK, $headers);
    }

    private function findFile(Context $context, string $fileId): ImportExportFileEntity
    {
        
return $this->filesystem->read($path);
    }

    /** * {@inheritdoc} */
    public function readStream($path)
    {
        $this->migrateFileLive($path);
        $path = $this->strategy->encode($path);

        return $this->filesystem->readStream($path);
    }

    /** * {@inheritdoc} */
    public function getUrl($path)
    {
        if (empty($path)) {
            return null;
        }

        
public function loadMediaFile(string $mediaId, Context $context): string
    {
        $media = $this->findMediaById($mediaId$context);

        return $this->getFileSystem($media)->read($this->getFilePath($media)) ?: '';
    }

    public function loadMediaFileStream(string $mediaId, Context $context): StreamInterface
    {
        $media = $this->findMediaById($mediaId$context);
        $resource = $this->getFileSystem($media)->readStream($this->getFilePath($media));

        return $this->streamFactory->createStreamFromResource($resource);
    }

    private function getFilePath(MediaEntity $media): string
    {
        $this->fileNameValidator->validateFileName($media->getFileName() ?: '');

        return $this->urlGenerator->getRelativeMediaUrl($media);
    }

    
return;
        }

        @set_time_limit(0);

        $response->headers->set('content-type', $mimeType);
        $response->headers->set('content-disposition', sprintf('attachment; filename="%s"', basename($location)));
        $response->headers->set('content-length', $meta['size']);
        $response->headers->set('content-transfer-encoding', 'binary');
        $response->sendHeaders();

        $upstream = $filesystem->readStream($location);
        if (!\is_resource($upstream)) {
            throw new RuntimeException(sprintf('Could not read stream from: %s', $location));
        }
        $downstream = fopen('php://output', 'wb');
        if (!\is_resource($downstream)) {
            throw new RuntimeException('Could not create temp stream');
        }

        if (!$this->unitTestMode) {
            ob_end_clean();
        }

        


    private function getDefaultResponse(MediaEntity $media, SalesChannelContext $context, FilesystemOperator $fileSystem): Response
    {
        if (!$media->isPrivate()) {
            return new RedirectResponse($this->urlGenerator->getAbsoluteMediaUrl($media));
        }

        switch ($this->localPrivateDownloadStrategy) {
            case self::X_SENDFILE_DOWNLOAD_STRATEGRY:
                $location = $this->urlGenerator->getRelativeMediaUrl($media);
                $stream = $fileSystem->readStream($location);
                $location = \is_resource($stream) ? stream_get_meta_data($stream)['uri'] : $location;

                $response = new Response(null, 200, $this->getStreamHeaders($media));
                $response->headers->set('X-Sendfile', $location);

                return $response;
            case self::X_ACCEL_DOWNLOAD_STRATEGRY:
                $location = $this->urlGenerator->getRelativeMediaUrl($media);

                $response = new Response(null, 200, $this->getStreamHeaders($media));
                $response->headers->set('X-Accel-Redirect', $location);

                

    public function getBody()
    {
        if($this->stream != null) {
            $this->readStream();
        }
        return parent::getBody();
    }

    /** * Get the raw response body (as transfered "on wire") as string * * If the body is encoded (with Transfer-Encoding, not content-encoding - * IE "chunked" body), gzip compressed, etc. it will not be decoded. * * @return string */
private function downloadImage(string $destination): string
    {
        $tmpFilename = tempnam(sys_get_temp_dir(), 'optimize_image');
        if (!\is_string($tmpFilename)) {
            throw new RuntimeException('Could not create tmp file name');
        }
        $handle = fopen($tmpFilename, 'wb');
        if (!\is_resource($handle)) {
            throw new RuntimeException(sprintf('Could not open file at: %s', $tmpFilename));
        }

        $fromHandle = $this->mediaService->readStream($destination);
        if (!\is_resource($fromHandle)) {
            throw new RuntimeException(sprintf('Could not open file at: %s', $destination));
        }
        stream_copy_to_stream(
            $fromHandle,
            $handle
        );

        return $tmpFilename;
    }

    


    private function printErrors(ImportExport $importExport, ImportExportLogEntity $log, SymfonyStyle $io, bool $deleteLog): void
    {
        if (!$importExport->getLogEntity()->getInvalidRecordsLog() || !$log->getFile()) {
            return;
        }

        $config = Config::fromLog($importExport->getLogEntity()->getInvalidRecordsLog());
        $reader = new CsvReader();
        $invalidLogFilePath = $log->getFile()->getPath() . '_invalid';
        $resource = $this->filesystem->readStream($invalidLogFilePath);

        $invalidRows = $reader->read($config$resource, 0);

        foreach ($invalidRows as $invalidRow) {
            $io->note($invalidRow['_error']);
            $io->newLine();
        }

        if ($deleteLog) {
            $this->filesystem->delete($invalidLogFilePath);
            $this->filesystem->delete($log->getFile()->getPath());
        }
Home | Imprint | This part of the site doesn't use cookies.