This commit is contained in:
Mateusz 2026-06-24 07:12:14 +00:00 committed by GitHub
commit 5aa20dd66c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 66 additions and 0 deletions

View file

@ -42,6 +42,8 @@
{{ form_row(image_form.position, sylius_test_form_attribute('position')) }}
</div>
{% endif %}
{{ form_widget(image_form.cachedFilePath) }}
{{ form_widget(image_form.cachedFileName) }}
</div>
</div>
{% endfor %}

View file

@ -15,11 +15,17 @@ namespace Sylius\Bundle\CoreBundle\Form\Type;
use Sylius\Bundle\ResourceBundle\Form\Type\AbstractResourceType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\HttpFoundation\File\UploadedFile;
abstract class ImageType extends AbstractResourceType
{
private const CACHED_UPLOADS_SUBDIR = 'sylius_cached_uploads';
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
@ -30,11 +36,68 @@ abstract class ImageType extends AbstractResourceType
->add('file', FileType::class, [
'label' => 'sylius.form.image.file',
])
->add('cachedFilePath', HiddenType::class, [
'mapped' => false,
'required' => false,
])
->add('cachedFileName', HiddenType::class, [
'mapped' => false,
'required' => false,
])
;
$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event): void {
$data = $event->getData();
if (isset($data['file']) && $data['file'] instanceof UploadedFile) {
$uploadedFile = $data['file'];
$tempDir = $this->getCachedUploadsDir();
if (!is_dir($tempDir)) {
mkdir($tempDir, 0755, true);
}
$cachedFileName = uniqid('cached_', true) . '_' . $uploadedFile->getClientOriginalName();
copy($uploadedFile->getPathname(), $tempDir . '/' . $cachedFileName);
$data['cachedFilePath'] = $cachedFileName;
$data['cachedFileName'] = $uploadedFile->getClientOriginalName();
$event->setData($data);
return;
}
if (empty($data['file']) && !empty($data['cachedFilePath']) && !empty($data['cachedFileName'])) {
$tempDir = $this->getCachedUploadsDir();
$cachedFilePath = $tempDir . '/' . basename($data['cachedFilePath']);
if (file_exists($cachedFilePath)) {
$data['file'] = new UploadedFile(
$cachedFilePath,
$data['cachedFileName'],
null,
null,
true,
);
$event->setData($data);
}
}
});
}
public function getBlockPrefix(): string
{
return 'sylius_image';
}
public static function getCachedUploadsDirPath(): string
{
return sys_get_temp_dir() . '/' . self::CACHED_UPLOADS_SUBDIR;
}
private function getCachedUploadsDir(): string
{
return self::getCachedUploadsDirPath();
}
}

View file

@ -84,5 +84,6 @@
<service id="sylius.console.command.show_plus_info" class="Sylius\Bundle\CoreBundle\Console\Command\ShowPlusInfoCommand">
<tag name="console.command" />
</service>
</services>
</container>