Skip to content

Commit

Permalink
Merge pull request #11 from intaro/upload-content
Browse files Browse the repository at this point in the history
feat: Добавлен метод, позволяющий загружать напрямую контент файлов
  • Loading branch information
1on authored Jul 25, 2022
2 parents 56ee32f + 12e2342 commit 2e60507
Show file tree
Hide file tree
Showing 3 changed files with 94 additions and 109 deletions.
27 changes: 13 additions & 14 deletions DependencyInjection/IntaroFileUploaderExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,17 @@

namespace Intaro\FileUploaderBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;

class IntaroFileUploaderExtension extends Extension implements PrependExtensionInterface
{
public function prepend(ContainerBuilder $container)
public function prepend(ContainerBuilder $container): void
{
$configs = $container->getExtensionConfig($this->getAlias());
$config = $this->processConfiguration(new Configuration(), $configs);
Expand All @@ -31,29 +31,28 @@ public function prepend(ContainerBuilder $container)
'%intaro_file_uploader.class%',
[
new Reference("gaufrette.{$name}_filesystem"),
new Reference("router"),
$options['path'],
$options['allowed_types']
$options['allowed_types'],
]
));
}
}
}

public function load(array $configs, ContainerBuilder $container)
public function load(array $configs, ContainerBuilder $container): void
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);

$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
$loader->load('services.yml');
}

protected function generateGaufretteConfig($config)
{
$filesystems = [];
$adapters = [];

if (isset($config['uploaders'])) {
foreach (array_filter($config['uploaders']) as $uploaderType => $uploaders) {
foreach ($uploaders as $name => $options) {
Expand All @@ -62,18 +61,18 @@ protected function generateGaufretteConfig($config)
$options['path']
);
$filesystems[$name] = [
'adapter' => $name
'adapter' => $name,
];
$adapters[$name] = [
$uploaderType => $options
$uploaderType => $options,
];
}
}
}

$gaufretteConfig = [
'adapters' => $adapters,
'filesystems' => $filesystems
'filesystems' => $filesystems,
];

return $gaufretteConfig;
Expand Down
168 changes: 77 additions & 91 deletions Services/FileUploader.php
Original file line number Diff line number Diff line change
@@ -1,53 +1,35 @@
<?php

namespace Intaro\FileUploaderBundle\Services;

use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\File\File;
use Gaufrette\Filesystem;
use Gaufrette\Adapter\Local;
use Gaufrette\Adapter\AwsS3;
use Symfony\Component\Routing\RouterInterface;
use Gaufrette\Adapter\Local;
use Gaufrette\Filesystem;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\File\UploadedFile;

/**
* Class FileUploader
*
* @package Intaro\FileUploaderBundle\Services
*/
class FileUploader
{
private $filesystem;
private $path;
private $allowedTypes;
private $router;
private $translator;
private Filesystem $filesystem;
private string $path;
private ?array $allowedTypes;
private \Transliterator $translator;

/**
* Constructor
*
* @param mixed $container app container
*/
public function __construct(
Filesystem $filesystem,
RouterInterface $router,
$path,
$allowedTypes
string $path,
array $allowedTypes
) {
$this->filesystem = $filesystem;
$this->path = $path;
$this->allowedTypes = $allowedTypes;
$this->router = $router;
$this->translator = \Transliterator::create('Any-Latin;Latin-ASCII;Lower;[\u0080-\u7fff] remove');
}

/**
* Upload method
*
* @param UploadedFile $file file to upload
*
* @return string
* @throws \InvalidArgumentException
*/
public function upload(UploadedFile $file)
public function upload(UploadedFile $file): string
{
$fileMimeType = $file->getMimeType();
if ($this->allowedTypes && !in_array($fileMimeType, $this->allowedTypes)) {
Expand All @@ -72,55 +54,7 @@ public function upload(UploadedFile $file)
return $filename;
}

/**
* Generate new filename based on original name
*
* @param string $originalName
* @return string
*/
public function generateNameByOriginal($originalName)
{
return sprintf(
'%s-%s',
uniqid(),
$this->clearName($originalName)
);
}

/**
* Name cleanup
* @param $originalName
* @return string
*/
protected function clearName($originalName)
{
//basic check on URL encoding
if (urldecode($originalName) !== $originalName) {
$originalName = urldecode($originalName);
}

$originalName = preg_replace(
'/[\+\\/\%\#\?]+/',
'_',
$originalName
);

return preg_replace(
'/\s+/',
'-',
$this->translator->transliterate($originalName)
);
}

/**
* Upload local file to storage
*
* @access public
* @param mixed $pathname
* @param bool $unlinkAfterUpload (default: true)
* @return string
*/
public function uploadByPath($pathname, $unlinkAfterUpload = true)
public function uploadByPath(string $pathname, bool $unlinkAfterUpload = true): string
{
$file = new File($pathname);
$filename = $file->getBasename();
Expand Down Expand Up @@ -150,59 +84,111 @@ public function uploadByPath($pathname, $unlinkAfterUpload = true)
return $filename;
}

public function remove($name)
public function uploadByContent(string $fileContent, string $filename, string $mimeType): string
{
if ($this->allowedTypes && !in_array($mimeType, $this->allowedTypes)) {
throw new \InvalidArgumentException(
sprintf('Files of type %s are not allowed.', $mimeType)
);
}

$adapter = $this->filesystem->getAdapter();

if (!($adapter instanceof Local)) {
$adapter->setMetadata(
$filename,
['contentType' => $mimeType]
);
}

$adapter->write($filename, $fileContent);

return $filename;
}

public function generateNameByOriginal(string $originalName): string
{
return sprintf(
'%s-%s',
uniqid(),
$this->clearName($originalName)
);
}

protected function clearName(string $originalName): string
{
//basic check on URL encoding
if (urldecode($originalName) !== $originalName) {
$originalName = urldecode($originalName);
}

$originalName = preg_replace(
'/[\+\\/\%\#\?]+/',
'_',
$originalName
);

return preg_replace(
'/\s+/',
'-',
$this->translator->transliterate($originalName)
);
}

public function remove($name): bool
{
return $this->filesystem->delete($name);
}

public function getUrl($name)
public function getUrl($name): string
{
return $this->getPath().$name;
return $this->getPath() . $name;
}

public function listFiles()
/** @return string[] */
public function listFiles(): array
{
$files = [];
$keys = $this->filesystem->listKeys();
$adapter = $this->filesystem->getAdapter();
if ($adapter instanceof AwsS3) {
if (sizeof($keys) > 0) {
if (count($keys) > 0) {
foreach ($keys as $file) {
$filename = basename($file);
if ($filename) {
$files[] = $this->getPath().$filename;
$files[] = $this->getPath() . $filename;
}
}
}
} elseif ($adapter instanceof Local) {
if (isset($keys['keys']) && sizeof($keys['keys']) > 0) {
if (isset($keys['keys']) && count($keys['keys']) > 0) {
foreach ($keys['keys'] as $file) {
$files[] = $this->getPath().$file;
$files[] = $this->getPath() . $file;
}
}
}

return $files;
}

public function getFilesystem()
public function getFilesystem(): Filesystem
{
return $this->filesystem;
}

public function setFilesystem($filesystem)
public function setFilesystem(Filesystem $filesystem): self
{
$this->filesystem = $filesystem;

return $this;
}

public function getPath()
public function getPath(): string
{
return $this->path;
}

public function getAllowedTypes()
public function getAllowedTypes(): ?array
{
return $this->allowedTypes;
}
Expand Down
8 changes: 4 additions & 4 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@
}
],
"require": {
"knplabs/knp-gaufrette-bundle": "~0.3"
"knplabs/knp-gaufrette-bundle": "~0.3",
"php": "^7.4"
},
"autoload": {
"psr-0": {
"psr-4": {
"Intaro\\FileUploaderBundle\\": ""
}
},
"target-dir" : "Intaro/FileUploaderBundle"
}
}

0 comments on commit 2e60507

Please sign in to comment.