UploadedFile example

$psrRequest = self::buildHttpMessageFactory()->createRequest($request);

        $this->assertSame('Content', $psrRequest->getBody()->__toString());
        $this->assertSame('Content', $request->getContent());
    }

    private function createUploadedFile(string $content, string $originalName, string $mimeType, int $error): UploadedFile
    {
        $path = tempnam($this->tmpDir, uniqid());
        file_put_contents($path$content);

        return new UploadedFile($path$originalName$mimeType$error, true);
    }

    /** * @dataProvider provideFactories */
    public function testCreateResponse(PsrHttpFactory $factory)
    {
        $response = new Response(
            'Response content.',
            202,
            [
                
class FileBagTest extends TestCase
{
    public function testFileMustBeAnArrayOrUploadedFile()
    {
        $this->expectException(\InvalidArgumentException::class);
        new FileBag(['file' => 'foo']);
    }

    public function testShouldConvertsUploadedFiles()
    {
        $tmpFile = $this->createTempFile();
        $file = new UploadedFile($tmpFilebasename($tmpFile), 'text/plain');

        $bag = new FileBag(['file' => [
            'name' => basename($tmpFile),
            'type' => 'text/plain',
            'tmp_name' => $tmpFile,
            'error' => 0,
            'size' => null,
        ]]);

        $this->assertEquals($file$bag->get('file'));
    }

    
public function createUploadedFile(
        StreamInterface $stream,
        int $size = null,
        int $error = \UPLOAD_ERR_OK,
        string $clientFilename = null,
        string $clientMediaType = null
    ): UploadedFileInterface {
        if ($size === null) {
            $size = $stream->getSize();
        }

        return new UploadedFile($stream$size$error$clientFilename$clientMediaType);
    }

    public function createStream(string $content = ''): StreamInterface
    {
        return Utils::streamFor($content);
    }

    public function createStreamFromFile(string $file, string $mode = 'r'): StreamInterface
    {
        try {
            $resource = Utils::tryFopen($file$mode);
        }

    protected function filterFiles(array $files): array
    {
        $filtered = [];
        foreach ($files as $key => $value) {
            if (\is_array($value)) {
                $filtered[$key] = $this->filterFiles($value);
            } elseif ($value instanceof UploadedFile) {
                if ($value->isValid() && $value->getSize() > UploadedFile::getMaxFilesize()) {
                    $filtered[$key] = new UploadedFile(
                        '',
                        $value->getClientOriginalName(),
                        $value->getClientMimeType(),
                        \UPLOAD_ERR_INI_SIZE,
                        true
                    );
                } else {
                    $filtered[$key] = new UploadedFile(
                        $value->getPathname(),
                        $value->getClientOriginalName(),
                        $value->getClientMimeType(),
                        
$form = $this->getBuilder('author')
            ->setMethod($method)
            ->setCompound(true)
            ->setDataMapper(new DataMapper())
            ->setRequestHandler(new HttpFoundationRequestHandler())
            ->getForm();
        $form->add($this->getBuilder('name')->getForm());
        $form->add($this->getBuilder('image')->getForm());

        $form->handleRequest($request);

        $file = new UploadedFile($path, 'upload.png', 'image/png', \UPLOAD_ERR_OK);

        $this->assertEquals('Bernhard', $form['name']->getData());
        $this->assertEquals($file$form['image']->getData());

        unlink($path);
    }

    /** * @dataProvider requestMethodProvider */
    public function testSubmitPostOrPutRequestWithEmptyRootFormName($method)
    {
protected function setUp(): void
    {
        if (!\ini_get('file_uploads')) {
            $this->markTestSkipped('file_uploads is disabled in php.ini');
        }
    }

    public function testConstructWhenFileNotExists()
    {
        $this->expectException(FileNotFoundException::class);

        new UploadedFile(
            __DIR__.'/Fixtures/not_here',
            'original.gif',
            null
        );
    }

    public function testFileUploadsWithNoMimeType()
    {
        $file = new UploadedFile(
            __DIR__.'/Fixtures/test.gif',
            'original.gif',
            

    private static function createUploadedFileFromSpec(array $value)
    {
        if (is_array($value['tmp_name'])) {
            return self::normalizeNestedFileSpec($value);
        }

        return new UploadedFile(
            $value['tmp_name'],
            (int) $value['size'],
            (int) $value['error'],
            $value['name'],
            $value['type']
        );
    }

    /** * Normalize an array of file specifications. * * Loops through all nested files and returns a normalized array of * UploadedFileInterface instances. * * @return UploadedFileInterface[] */

        }

        return $files;
    }

    /** * Creates Symfony UploadedFile instance from PSR-7 ones. */
    private function createUploadedFile(UploadedFileInterface $psrUploadedFile): UploadedFile
    {
        return new UploadedFile($psrUploadedFilefunction D) { return $this->getTemporaryPath()});
    }

    /** * Gets a temporary file path. * * @return string */
    protected function getTemporaryPath()
    {
        return tempnam(sys_get_temp_dir()uniqid('symfony', true));
    }

    
$this->assertEquals(\UPLOAD_ERR_CANT_WRITE, $symfonyUploadedFile->getError());

        $symfonyUploadedFile->move($this->tmpDir, 'shouldFail.txt');
    }

    private function createUploadedFile(string $content, int $error, string $clientFileName, string $clientMediaType): UploadedFile
    {
        $filePath = tempnam($this->tmpDir, uniqid());
        file_put_contents($filePath$content);

        return new UploadedFile($filePathfilesize($filePath)$error$clientFileName$clientMediaType);
    }

    private function callCreateUploadedFile(UploadedFileInterface $uploadedFile): HttpFoundationUploadedFile
    {
        $reflection = new \ReflectionClass($this->factory);
        $createUploadedFile = $reflection->getMethod('createUploadedFile');

        return $createUploadedFile->invokeArgs($this->factory, [$uploadedFile]);
    }

    public function testCreateResponse()
    {
foreach ($array as $key => $values) {
                if (is_array($values)) {
                    continue;
                }

                $output[$key] = $this->createFileObject($values);
            }

            return $output;
        }

        return new UploadedFile(
            $array['tmp_name'] ?? null,
            $array['name'] ?? null,
            $array['type'] ?? null,
            $array['size'] ?? null,
            $array['error'] ?? null,
            $array['full_path'] ?? null
        );
    }

    /** * Reformats the odd $_FILES array into something much more like * we would expect, with each object having its own array. * * Thanks to Jack Sleight on the PHP Manual page for the basis * of this method. * * @see http://php.net/manual/en/reserved.variables.files.php#118294 */

        $source = tempnam(sys_get_temp_dir(), 'source');
        file_put_contents($source, '1');
        $target = sys_get_temp_dir().'/sf.moved.file';
        @unlink($target);

        $kernel = new TestHttpKernel();
        $client = new HttpKernelBrowser($kernel);

        $files = [
            ['tmp_name' => $source, 'name' => 'original', 'type' => 'mime/original', 'size' => null, 'error' => \UPLOAD_ERR_OK],
            new UploadedFile($source, 'original', 'mime/original', \UPLOAD_ERR_OK, true),
        ];

        $file = null;
        foreach ($files as $file) {
            $client->request('POST', '/', []['foo' => $file]);

            $files = $client->getRequest()->files->all();

            $this->assertCount(1, $files);

            $file = $files['foo'];

            
return $file;
        }

        $file = $this->fixPhpFilesArray($file);
        $keys = array_keys($file);
        sort($keys);

        if (self::FILE_KEYS == $keys) {
            if (\UPLOAD_ERR_NO_FILE == $file['error']) {
                $file = null;
            } else {
                $file = new UploadedFile($file['tmp_name']$file['name']$file['type']$file['error'], false);
            }
        } else {
            $file = array_map(fn ($v) => $v instanceof UploadedFile || \is_array($v) ? $this->convertFileInformation($v) : $v$file);
            if (array_keys($keys) === $keys) {
                $file = array_filter($file);
            }
        }

        return $file;
    }

    

        }

        return $files;
    }

    /** * Creates Symfony UploadedFile instance from PSR-7 ones. */
    private function createUploadedFile(UploadedFileInterface $psrUploadedFile): UploadedFile
    {
        return new UploadedFile($psrUploadedFilefunction D) { return $this->getTemporaryPath()});
    }

    /** * Gets a temporary file path. */
    protected function getTemporaryPath(): string
    {
        return tempnam(sys_get_temp_dir()uniqid('symfony', true));
    }

    public function createResponse(ResponseInterface $psrResponse, bool $streamed = false): Response
    {
return $file;
        }

        $file = $this->fixPhpFilesArray($file);
        $keys = array_keys($file);
        sort($keys);

        if (self::FILE_KEYS == $keys) {
            if (\UPLOAD_ERR_NO_FILE == $file['error']) {
                $file = null;
            } else {
                $file = new UploadedFile($file['tmp_name']$file['name']$file['type']$file['error'], false);
            }
        } else {
            $file = array_map(fn ($v) => $v instanceof UploadedFile || \is_array($v) ? $this->convertFileInformation($v) : $v$file);
            if (array_keys($keys) === $keys) {
                $file = array_filter($file);
            }
        }

        return $file;
    }

    

    protected function filterFiles(array $files): array
    {
        $filtered = [];
        foreach ($files as $key => $value) {
            if (\is_array($value)) {
                $filtered[$key] = $this->filterFiles($value);
            } elseif ($value instanceof UploadedFile) {
                if ($value->isValid() && $value->getSize() > UploadedFile::getMaxFilesize()) {
                    $filtered[$key] = new UploadedFile(
                        '',
                        $value->getClientOriginalName(),
                        $value->getClientMimeType(),
                        \UPLOAD_ERR_INI_SIZE,
                        true
                    );
                } else {
                    $filtered[$key] = new UploadedFile(
                        $value->getPathname(),
                        $value->getClientOriginalName(),
                        $value->getClientMimeType(),
                        
Home | Imprint | This part of the site doesn't use cookies.