PHP code example of arxy / files

1. Go to this page and download the library: Download arxy/files library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

arxy / files example snippets




namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity()
 * @ORM\Table()
 */
class File extends \Arxy\FilesBundle\Entity\File
{
    /**
     * @var int|null
     * @ORM\Id()
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue()
     */
    protected $id;

    /**
     * @return int|null
     */
    public function getId(): ?int
    {
        return $this->id;
    }

    /**
     * @param int|null $id
     */
    public function setId(?int $id): void
    {
        $this->id = $id;
    }
}



namespace App\Entity;

use Arxy\FilesBundle\Model\File;use Doctrine\ORM\Mapping as ORM;
use Arxy\FilesBundle\Entity\EmbeddableFile;

/**
 * @ORM\Entity()
 * @ORM\Table()
 */
class News
{
    /** @ORM\Embedded(class=EmbeddableFile::class) */
    private ?EmbeddableFile $image = null;
    
    public function getImage(): ?File {
        return $this->image;
    }
    
    public function setImage(?File $file) {
        $this->image = $file;
    }
}



namespace App\Repository;

use Arxy\FilesBundle\Repository;
use Doctrine\ORM\EntityRepository;
use \Arxy\FilesBundle\Repository\ORM;

class FileRepository extends EntityRepository implements Repository
{
   use ORM;
}

$adapter = new \League\Flysystem\Local\LocalFilesystemAdapter;
$filesystem = new \League\Flysystem\Filesystem($adapter);

$storage = new \Arxy\FilesBundle\Storage\FlysystemStorage($filesystem);

$namingStrategy = new \Arxy\FilesBundle\NamingStrategy\SplitHashStrategy();

$repository = new FileRepository();

$fileManager = new \Arxy\FilesBundle\Manager(\App\Entity\File::class, $storage, $namingStrategy, $repository);

$file = new \SplFileInfo($pathname);
$fileEntity = $fileManager->upload($file);

$file = $request->files->get('file');
$fileEntity = $fileManager->upload($file);

$entityManager->persist($fileEntity);
$entityManager->flush();


$file = new \SplFileInfo($pathname);
$embeddableFile = $fileManager->upload($file);

$news = new \App\Entity\News();
$news->setImage($embeddableFile);

$entityManager->persist($news);
$entityManager->flush();


$formBuilder->add(
    'image',
    FileType::class,
    [
        's' => [
            'attr' => [
                'accept' => 'image/*',
            ],
            'constraints' => [
                   SymfonyConstraintsOnFiles
            ]
        ],
    ]
);

$file = $entityManager->find(File::class, 1);

$content = $fileManager->read($file);

$file = $entityManager->find(File::class, 1);

$fileHandle = $fileManager->readStream($file);



declare(strict_types=1);

namespace App\Controller;

use App\Entity\File;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Arxy\FilesBundle\Utility\DownloadUtility;
use Symfony\Component\HttpFoundation\Response;

class FileController extends AbstractController
{
    /**
     * @Route(path="/file/{id}", name="file_download")
     */
    public function download(
        string $id, 
        EntityManagerInterface $em, 
        DownloadUtility $downloadUtility
    ): Response {
        $file = $em->getRepository(File::class)->findOneBy(
            [
                'md5Hash' => $id,
            ]
        );

        if ($file === null) {
            throw $this->createNotFoundException('File not found');
        }

        return $downloadUtility->createResponse($file);
    }
}



declare(strict_types=1);

namespace App\Controller;

use App\Entity\File;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Arxy\FilesBundle\Utility\DownloadUtility;
use Arxy\FilesBundle\Utility\DownloadableFile;
use Symfony\Component\HttpFoundation\Response;

class FileController extends AbstractController
{
    /**
     * @Route(path="/file/{id}", name="file_download")
     */
    public function download(
        string $id,
        EntityManagerInterface $em, 
        DownloadUtility $downloadUtility
    ): Response {
        $file = $em->getRepository(File::class)->findOneBy(
            [
                'md5Hash' => $id,
            ]
        );

        if ($file === null) {
            throw $this->createNotFoundException('File not found');
        }

        return $downloadUtility->createResponse(new DownloadableFile($file, 'my_name.jpg', false, new \DateTimeImmutable('date of cache expiry')));
    }
}



declare(strict_types=1);

namespace App\Serializer;

use App\Entity\File;
use Arxy\FilesBundle\PathResolver;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;

class FileNormalizer implements NormalizerInterface
{
    private ObjectNormalizer $objectNormalizer;
    private PathResolver $pathResolver;

    public function __construct(
        ObjectNormalizer $objectNormalizer,
        PathResolver $pathResolver
    ) {
        $this->objectNormalizer = $objectNormalizer;
        $this->pathResolver = $pathResolver;
    }

    public function normalize($object, $format = null, array $context = array())
    {
        assert($object instanceof File);
        $data = $this->objectNormalizer->normalize($object, $format, $context);
        $data['url'] = $this->pathResolver->getPath($object);

        return $data;
    }

    public function supportsNormalization($data, $format = null)
    {
        return $data instanceof File;
    }
}

    /**
     * @var string
     * @Groups({"file_read"})
     */
    private string $url = null;

    public function getUrl(): array
    {
        return $this->url;
    }

    public function setUrl(string $url): void
    {
        $this->url = $url;
    }

    /**
     * @var array
     * @Groups({"file_read"})
     */
    private $formats = [];

    public function getFormats(): array
    {
        return $this->formats;
    }

    public function setFormats(array $formats): void
    {
        $this->formats = $formats;
    }



declare(strict_types=1);

namespace App\Serializer;

use App\Entity\File;
use Arxy\FilesBundle\LiipImagine\FileFilter;use Arxy\FilesBundle\LiipImagine\FileFilterPathResolver;use Liip\ImagineBundle\Imagine\Filter\FilterConfiguration;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;

class FileNormalizer implements NormalizerInterface
{
    private ObjectNormalizer $objectNormalizer;
    private FileFilterPathResolver $fileFilterPathResolver;
    private FilterConfiguration $filterConfiguration;

    public function __construct(
        ObjectNormalizer $objectNormalizer,
        FileFilterPathResolver $fileFilterPathResolver,
        FilterConfiguration $filterConfiguration
    ) {
        $this->objectNormalizer = $objectNormalizer;
        $this->fileFilterPathResolver = $fileFilterPathResolver;
        $this->filterConfiguration = $filterConfiguration;
    }

    public function normalize($object, $format = null, array $context = array())
    {
        assert($object instanceof \Arxy\FilesBundle\Model\File);
        $data = $this->objectNormalizer->normalize($object, $format, $context);

        $data['formats'] = array_reduce(
            array_keys($this->filterConfiguration->all()),
            function ($array, $filter) use ($object) {
                $array[$filter] = $this->fileFilterPathResolver->getUrl(new FileFilter($object, $filter));

                return $array;
            },
            []
        );

        return $data;
    }

    public function supportsNormalization($data, $format = null)
    {
        return $data instanceof \Arxy\FilesBundle\Model\File;
    }
}

class MyFactory implements \Arxy\FilesBundle\PathResolver\AzureBlobStorageSASParametersFactory 
{
    public function create(\Arxy\FilesBundle\Model\File $file) : \Arxy\FilesBundle\PathResolver\AzureBlobStorageSASParameters
    {
        return new \Arxy\FilesBundle\PathResolver\AzureBlobStorageSASParameters(
            new \DateTimeImmutable('+10 minutes'),
        );
    }
}

class VirtualFile extends \Arxy\FilesBundle\Model\DecoratedFile {

    private ?string $downloadFilename = null;
    
    public function setDownloadFilename(string $filename) {
        $this->downloadFilename = $filename;
    }
    
    public function getDownloadFilename(): ?string {
        return $this->downloadFilename;
    }
}

class VirtualFilePathResolver implements \Arxy\FilesBundle\PathResolver 
{
    public function getPath(\Arxy\FilesBundle\Model\File $file): string {
        assert($file instanceof VirtualFile);
        
        return sprintf('url?download_filename=%s', $file->getDownloadFilename());
    }
}

public function someAction(\Arxy\FilesBundle\PathResolver $pathResolver) {
    $virtualFile = new \Arxy\FilesBundle\Tests\VirtualFile($file);
    $virtualFile->setDownloadFilename('this_file_is_renamed_during_download.jpg');
    $downloadUrl = $pathResolver->getPath($virtualFile);
}



declare(strict_types=1);

namespace App\Controller\ApiPlatform;

use Arxy\FilesBundle\Manager;
use Arxy\FilesBundle\Model\File;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;

final class Upload
{
    private Manager $fileManager;

    public function __construct(Manager $fileManager)
    {
        $this->fileManager = $fileManager;
    }

    public function __invoke(Request $request): File
    {
        $uploadedFile = $request->files->get('file');
        if (!$uploadedFile) {
            throw new BadRequestHttpException('"file" is 



declare(strict_types=1);

namespace App\Entity;

use ApiPlatform\Core\Annotation\ApiResource;
use App\Controller\ApiPlatform\Upload;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation\Groups;

/**
 * @ORM\Entity
 * @ORM\Table(name="files")
 * @ApiResource(
 *     iri="http://schema.org/MediaObject",
 *     normalizationContext={
 *         "groups"={"file_read"}
 *     },
 *     collectionOperations={
 *         "post"={
 *             "controller"=Upload::class,
 *             "deserialize"=false,
 *             "validation_groups"={"Default"},
 *             "openapi_context"={
 *                 "requestBody"={
 *                     "content"={
 *                         "multipart/form-data"={
 *                             "schema"={
 *                                 "type"="object",
 *                                 "properties"={
 *                                     "file"={
 *                                         "type"="string",
 *                                         "format"="binary"
 *                                     }
 *                                 }
 *                             }
 *                         }
 *                     }
 *                 }
 *             }
 *         }
 *     },
 *     itemOperations={
 *         "get"
 *     }
 * )
 */
class File extends \Arxy\FilesBundle\Entity\File
{
    /**
     * @var int|null
     *
     * @ORM\Id
     * @ORM\Column(type="integer", nullable=false)
     * @ORM\GeneratedValue
     * @Groups({"file_read"})
     */
    protected ?int $id = null;

    public function getId(): ?int
    {
        return $this->id;
    }
}