1414namespace Sylius \ImportExport \Controller ;
1515
1616use Sylius \ImportExport \Messenger \Command \CreateImportProcess ;
17+ use Sylius \ImportExport \Uploader \ImportFileUploader ;
18+ use Sylius \Resource \Metadata \RegistryInterface ;
1719use Symfony \Component \Form \FormFactoryInterface ;
20+ use Symfony \Component \HttpFoundation \File \UploadedFile ;
1821use Symfony \Component \HttpFoundation \RedirectResponse ;
1922use Symfony \Component \HttpFoundation \Request ;
2023use Symfony \Component \HttpFoundation \Response ;
@@ -27,6 +30,8 @@ public function __construct(
2730 private FormFactoryInterface $ formFactory ,
2831 private MessageBusInterface $ commandBus ,
2932 private string $ importForm ,
33+ private ImportFileUploader $ importFileUploader ,
34+ private RegistryInterface $ metadataRegistry ,
3035 ) {
3136 }
3237
@@ -39,27 +44,43 @@ public function __invoke(Request $request, string $grid): Response
3944 $ form ->handleRequest ($ request );
4045
4146 if (!$ form ->isSubmitted () || !$ form ->isValid ()) {
42- $ session ->getFlashBag ()->add ('error ' , 'sylius_import_export.import_form_invalid ' );
47+ if ($ form ->isSubmitted ()) {
48+ $ errors = [];
49+ foreach ($ form ->getErrors (true ) as $ error ) {
50+ $ errors [] = $ error ->getMessage ();
51+ }
52+ $ errorMessage = !empty ($ errors ) ? implode (', ' , $ errors ) : 'sylius_import_export.import_form_invalid ' ;
53+ $ session ->getFlashBag ()->add ('error ' , $ errorMessage );
54+ } else {
55+ $ session ->getFlashBag ()->add ('error ' , 'sylius_import_export.import_form_invalid ' );
56+ }
4357
4458 return new RedirectResponse ($ request ->headers ->get ('referer ' ) ?? '/ ' );
4559 }
4660
4761 $ data = $ form ->getData ();
48- $ format = $ data ['format ' ];
49- $ filePath = $ data ['filePath ' ];
5062 $ resourceClass = $ data ['resourceClass ' ];
5163
64+ /** @var UploadedFile $file */
65+ $ file = $ data ['file ' ];
66+
5267 try {
68+ $ format = $ this ->importFileUploader ->getFormatFromMimeType ($ file ->getMimeType ());
69+ $ filePath = $ this ->importFileUploader ->upload ($ file );
70+
71+ $ metadata = $ this ->metadataRegistry ->getByClass ($ resourceClass );
72+ $ resourceAlias = $ metadata ->getAlias ();
73+
5374 $ this ->commandBus ->dispatch (new CreateImportProcess (
54- resource: $ resourceClass ,
75+ resource: $ resourceAlias ,
5576 format: $ format ,
5677 filePath: $ filePath ,
5778 parameters: [],
5879 ));
5980
6081 $ session ->getFlashBag ()->add ('success ' , 'sylius_import_export.import_started ' );
61- } catch (\Throwable ) {
62- $ session ->getFlashBag ()->add ('error ' , 'sylius_import_export.import_failed ' );
82+ } catch (\Throwable $ e ) {
83+ $ session ->getFlashBag ()->add ('error ' , 'sylius_import_export.upload_failed ' );
6384 }
6485
6586 return new RedirectResponse ($ request ->headers ->get ('referer ' ) ?? '/ ' );
0 commit comments