src/EventSubscriber/Taxonomy/TaxonResourceSubscriber.php line 31

  1. <?php
  2. namespace App\EventSubscriber\Taxonomy;
  3. use Symfony\Component\HttpFoundation\RequestStack;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\EventDispatcher\GenericEvent;
  6. use Webmozart\Assert\Assert;
  7. use Sylius\Component\Customer\Model\CustomerInterface;
  8. use App\Repository\Customer\CustomerRepository;
  9. use App\Entity\Channel\ChannelEcodaAccountInfo; 
  10. use App\Repository\Channel\ChannelEcodaAccountInfoRepository;
  11. use App\Repository\Channel\ChannelEcodaAccountTypeRepository;
  12. use Doctrine\ORM\EntityManagerInterface;
  13. use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
  14. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  15. use App\Manager\EcodaAccountManager;
  16. use App\Entity\Taxon\TaxonVariant;
  17. use App\Entity\Taxonomy\Taxon;
  18. use Sylius\Component\Taxonomy\Repository\TaxonRepositoryInterface;
  19. class TaxonResourceSubscriber  implements EventSubscriberInterface
  20. { 
  21.     private $taxonRepository;
  22.      
  23.     public function __construct(RequestStack $request, TaxonRepositoryInterface $taxonRepository)
  24.     { 
  25.         $this->taxonRepository = $taxonRepository;
  26.     }
  27.     public function onPreCreate(GenericEvent $event)
  28.     {  
  29.         $entity = $event->getSubject();  
  30.         Assert::isInstanceOf($entity, Taxon::class);  
  31.         $code = null;
  32.         $words = explode(' ',$entity->getName());
  33.         foreach ($words as $word) {
  34.             $code = $code.substr($word, 0, 1);
  35.         }  
  36.         $i = 1; 
  37.         while ($this->taxonRepository->findOneBy(['code'=> strtolower($code.'-'.$i)])) {
  38.             $i++; 
  39.         }
  40.         $code =  strtolower($code.'-'.$i);
  41.         $entity->setCode($code);
  42.     } 
  43.      
  44.  
  45.     public static function getSubscribedEvents()
  46.     {
  47.         return [
  48.            'sylius.taxon.pre_create' => 'onPreCreate',  
  49.         ];
  50.     }
  51. }