custom/plugins/CioSponsoredOrderConfirmation/src/Subscriber/CheckoutSubscriber.php line 86

Open in your IDE?
  1. <?php
  2. namespace CioSponsoredOrderConfirmation\Subscriber;
  3. use Exception;
  4. use Shopware\Core\Checkout\Cart\Event\CheckoutOrderPlacedEvent;
  5. use Shopware\Core\Checkout\Order\Aggregate\OrderTransaction\OrderTransactionEntity;
  6. use Shopware\Core\Checkout\Payment\PaymentMethodEntity;
  7. use Shopware\Core\Content\Media\Event\MediaFileExtensionWhitelistEvent;
  8. use Shopware\Core\Content\Media\File\FileNameProvider;
  9. use Shopware\Core\Content\Media\File\FileSaver;
  10. use Shopware\Core\Content\Media\File\MediaFile;
  11. use Shopware\Core\Framework\Context;
  12. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
  13. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  14. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
  15. use Shopware\Core\Framework\Util\Random;
  16. use Shopware\Core\Framework\Uuid\Uuid;
  17. use Shopware\Core\Framework\Validation\DataValidationDefinition;
  18. use Shopware\Core\Framework\Validation\DataValidator;
  19. use Shopware\Core\Framework\Validation\Exception\ConstraintViolationException;
  20. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  21. use Symfony\Component\HttpFoundation\File\UploadedFile;
  22. use Symfony\Component\HttpFoundation\Request;
  23. use Symfony\Component\HttpFoundation\RequestStack;
  24. use Symfony\Component\Validator\Constraints\File;
  25. use Throwable;
  26. class CheckoutSubscriber implements EventSubscriberInterface
  27. {
  28.     private ?Request $request;
  29.     private EntityRepositoryInterface $orderRepository;
  30.     private FileSaver $mediaUpdater;
  31.     private FileNameProvider $fileNameProvider;
  32.     private EntityRepositoryInterface $mediaRepository;
  33.     private EntityRepositoryInterface $mediaFolderRepository;
  34.     private DataValidator $dataValidator;
  35.     public function __construct(RequestStack $requestStackEntityRepositoryInterface $orderRepositoryFileSaver $mediaUpdaterFileNameProvider $fileNameProviderEntityRepositoryInterface $mediaRepositoryEntityRepositoryInterface $mediaFolderRepositoryDataValidator $dataValidator)
  36.     {
  37.         $this->request $requestStack->getCurrentRequest();
  38.         $this->orderRepository $orderRepository;
  39.         $this->mediaUpdater $mediaUpdater;
  40.         $this->fileNameProvider $fileNameProvider;
  41.         $this->mediaRepository $mediaRepository;
  42.         $this->mediaFolderRepository $mediaFolderRepository;
  43.         $this->dataValidator $dataValidator;
  44.     }
  45.     public static function getSubscribedEvents(): array
  46.     {
  47.         // Return the events to listen to as array like this:  <event to listen to> => <method to execute>
  48.         return [
  49.             CheckoutOrderPlacedEvent::class => 'onCheckoutOrderPlacedEvent',
  50.             'framework.validation.order.create' => 'onValidateOrder',
  51.             MediaFileExtensionWhitelistEvent::class => 'onMediaFileExtensionWhitelistEvent'
  52.         ];
  53.     }
  54.     public function onValidateOrder()
  55.     {
  56.         $data $this->request->files;
  57.         foreach ($data as $file) {
  58.             /** @var UploadedFile $file */
  59.             if ($file) {
  60.                 $definition = new DataValidationDefinition('sponsoringInformationsClubLogo');
  61.                 $definition->add('sponsoringInformationsClubLogo', new File(null'2m'null, [
  62.                     'image/x-eps'// eps
  63.                     'application/postscript'// eps, ai
  64.                     'application/pdf'//ai
  65.                     'image/svg+xml'
  66.                 ]));
  67.                 $violations $this->dataValidator->getViolations($data->all(), $definition);
  68.                 if (!$violations->count()) {
  69.                     return;
  70.                 }
  71.                 throw new ConstraintViolationException($violations$data->all());
  72.             }
  73.         }
  74.     }
  75.     public function onMediaFileExtensionWhitelistEvent(MediaFileExtensionWhitelistEvent $event)
  76.     {
  77.         $event->setWhitelist(array_merge($event->getWhitelist(), ['ai']));
  78.     }
  79.     public function onCheckoutOrderPlacedEvent(CheckoutOrderPlacedEvent $event)
  80.     {
  81.         $customFields = [];
  82.         if ($currentCustomFields $event->getOrder()->getCustomFields()) {
  83.             if (is_array($currentCustomFields)) {
  84.                 $customFields $currentCustomFields;
  85.             }
  86.         }
  87.         if ( $this->request &&
  88.             $event->getOrder()->getTransactions()->first() instanceof OrderTransactionEntity &&
  89.             $event->getOrder()->getTransactions()->first()->getPaymentMethod() instanceof PaymentMethodEntity &&
  90.             $event->getOrder()->getTransactions()->first()->getPaymentMethod()->getName() == 'Kostenstelle Sponsoring'
  91.         ) {
  92.             $mediaIds $this->uploadMedia($this->request);
  93.             $customFields array_merge($customFields, [
  94.                 'sponsoringBasicInformations' => [
  95.                     'sponsoringInformationsPeriodFrom' => $this->request->request->get('sponsoringInformationsPeriodFrom'),
  96.                     'sponsoringInformationsPeriodTo' => $this->request->request->get('sponsoringInformationsPeriodTo'),
  97.                     'sponsoringInformationsStoreNumber' => $this->request->request->get('sponsoringInformationsStoreNumber'),
  98.                     'sponsoringInformationsClubName' => $this->request->request->get('sponsoringInformationsClubName'),
  99.                     'sponsoringInformationsClubLogo' => $mediaIds,
  100.                     'sponsoringInformationsClubContactPerson' => $this->request->request->get('sponsoringInformationsClubContactPerson'),
  101.                     'sponsoringInformationsClubAddress' => $this->request->request->get('sponsoringInformationsClubAddress'),
  102.                     'sponsoringInformationsActionShortDescription' => $this->request->request->get('sponsoringInformationsActionShortDescription'),
  103.                     'sponsoringInformationsOtherArticleInformations' => $this->request->request->get('sponsoringInformationsOtherArticleInformations'),
  104.                 ]
  105.             ]);
  106.         }
  107.         $event->getOrder()->setCustomFields($customFields);
  108.         try {
  109.             $this->orderRepository->update([
  110.                 [
  111.                     'id' => $event->getOrder()->getId(),
  112.                     'customFields' => $customFields
  113.                 ]
  114.             ], $event->getContext());
  115.         } catch (Throwable $e) {
  116.         }
  117.     }
  118.     protected function uploadMedia(Request $request): array
  119.     {
  120.         $mediaIds = [];
  121.         $data $request->files;
  122.         $context Context::createDefaultContext();
  123.         $mediaRepository $this->mediaRepository;
  124.         foreach ($data as $file) {
  125.             /** @var UploadedFile $file */
  126.             if ($file) {
  127.                 // *.ai werden durch den mime-type als application/pdf erkannt und dann als pdf gespeichert. daher müssen wir das an einigen Stellen manuell auf ai ändern
  128.                 $fileName $file->getClientOriginalName();
  129.                 $fileExtension pathinfo($fileNamePATHINFO_EXTENSION);
  130.                 $fileNameWithoutExtension pathinfo($fileNamePATHINFO_FILENAME);
  131.                 $mediaFolder $this->mediaFolderRepository->search((new Criteria())->addFilter(new EqualsFilter('name''Trikot Logos')), $context)->first();
  132.                 $mediaId Uuid::randomHex();
  133.                 $media = [
  134.                     [
  135.                         'id' => $mediaId,
  136.                         'mediaFolderId' => ($mediaFolder) ? $mediaFolder->getId() : null,
  137.                         'fileExtension' => ($fileExtension == 'ai') ? 'ai' $file->getExtension(),
  138.                         'mimeType' => ($fileExtension == 'ai') ? 'application/postscript' $file->getMimeType(),
  139.                     ]
  140.                 ];
  141.                 $mediaRepository->upsert($media$context);
  142.                 try {
  143.                     $this->upload($file$fileNameWithoutExtension$mediaId$context, ($fileExtension == 'ai') ? 'ai' null);
  144.                 } catch (Exception $exception) {
  145.                     $fileNameWithoutExtension $fileNameWithoutExtension '_' Random::getInteger(1001000) . Random::getInteger(1001000);
  146.                     $this->upload($file$fileNameWithoutExtension$mediaId$context, ($fileExtension == 'ai') ? 'ai' null);
  147.                 }
  148.                 if ($fileExtension == 'ai') {
  149.                     //noch mal updaten, da beim upload was anderes gespeichert wird
  150.                     $this->mediaRepository->update($media$context);
  151.                 }
  152.                 $mediaIds[] = $mediaId;
  153.             }
  154.         }
  155.         return $mediaIds;
  156.     }
  157.     protected function upload($file$fileName$mediaId$context$fileExtension null)
  158.     {
  159.         $this->mediaUpdater->persistFileToMedia(
  160.             new MediaFile(
  161.                 $file->getRealPath(),
  162.                 $file->getMimeType(),
  163.                 $fileExtension ?: $file->guessExtension(),
  164.                 $file->getSize()
  165.             ),
  166.             $this->fileNameProvider->provide(
  167.                 $fileName,
  168.                 $file->getExtension(),
  169.                 $mediaId,
  170.                 $context
  171.             ),
  172.             $mediaId,
  173.             $context
  174.         );
  175.     }
  176. }