/** * onCreate * * Event listener that handles the creation of an entity. * * @param EntityServiceEvent $event * * @throws Exception\InvalidArgumentException If the entity is invalid. * @throws Exception\EntityNotCreatedException If the entity cannot be created. */ public function onCreate(EntityServiceEvent $event) { /** @var EntityRepositoryInterface $repository */ $repository = $event->getRepository(); /** @var EntityInterface $entity */ $entity = $event->getEntity(); $entity = $repository->create($entity, $event->flush()); $event->setEntity($entity); }
/** * onCreate * * Event listener that handles the creation of an entity. * * @param EntityServiceEvent $event * * @throws Exception\EntityServiceException * @throws Exception\InvalidEntityTypeException If the entity is invalid. * @throws Exception\EntityNotCreatedException If the entity failed to be created. */ public function onCreate(EntityServiceEvent $event) { try { /** @var EntityServiceInterface $entityService */ $entityService = $event->getTarget(); /** @var EntityRepositoryInterface $repository */ $repository = $event->getRepository(); /** @var EntityInterface $entity */ $entity = $event->getEntity(); $entityName = $entityService->getEntityName(); if (!$entity instanceof $entityName) { throw new Exception\InvalidEntityTypeException(sprintf('The entity must be of type \'%s\'; \'%s\' provided to \'%s\'.', $entityName, is_object($entity) ? get_class($entity) : gettype($entity), __METHOD__)); } $entity = $repository->create($entity, $event->flush()); $event->setEntity($entity); } catch (EntityRepositoryException $e) { throw new Exception\EntityNotCreatedException($e->getMessage(), $e->getCode(), $e); } catch (Exception\EntityServiceException $e) { throw $e; } }