src/Commands/DBImportCommand.php line 26

Open in your IDE?
  1. <?php
  2. namespace App\Commands;
  3. use Doctrine\DBAL\DriverManager;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use Exception;
  6. use InvalidArgumentException;
  7. use Symfony\Component\Console\Command\Command;
  8. use Symfony\Component\Console\Input\ArrayInput;
  9. use Symfony\Component\Console\Input\InputArgument;
  10. use Symfony\Component\Console\Input\InputInterface;
  11. use Symfony\Component\Console\Input\InputOption;
  12. use Symfony\Component\Console\Output\OutputInterface;
  13. use Symfony\Component\HttpKernel\KernelInterface;
  14. class DBImportCommand extends Command
  15. {
  16.     /** KernelInterface $appKernel */
  17.     protected static $defaultName 'flexx:database:import';
  18.     private $appKernel;
  19.     private $entityManager;
  20.     public function __construct(
  21.         $name null,  // removed string type-hint
  22.         KernelInterface $appKernel,
  23.         EntityManagerInterface $entityManager
  24.     )
  25.     {
  26.         $this->appKernel $appKernel;
  27.         $this->entityManager $entityManager;
  28.         parent::__construct($name);
  29.     }
  30.     /**
  31.      * {@inheritDoc}
  32.      */
  33.     protected function configure()
  34.     {
  35.         $this->setDescription('Prepare the database');
  36.         $this->addArgument('file'InputArgument::REQUIRED'Which file to import');
  37.     }
  38.     /**
  39.      * {@inheritDoc}
  40.      */
  41.     protected function execute(InputInterface $inputOutputInterface $output): int
  42.     {
  43.         // Import SQL File
  44.         $path $this->appKernel->getProjectDir();
  45.         $fileName $path DIRECTORY_SEPARATOR $input->getArgument('file');
  46.         $db $this->entityManager->getConnection()->getWrappedConnection();
  47.         if(file_exists($fileName)){
  48.             $sql trim(file_get_contents($fileName));
  49.             if($sql !== '' && $sql !== '0'){
  50.                 $db->beginTransaction();
  51.                 try{
  52.                     $querySet $db->prepare($sql);
  53.                     $querySet->execute();
  54.                     /*
  55.                     while($querySet->nextRowSet()){
  56.                         ++$count;
  57.                     }*/
  58.                 }catch(Exception $e){
  59.                     $db->rollBack();
  60.                     throw $e;
  61.                 }
  62.             }else{
  63.                 throw new Exception("File {$fileName} appears to be empty.");
  64.             }
  65.         }else{
  66.             throw new Exception("File '{$fileName}' not found.");
  67.         }
  68.         return Command::SUCCESS;
  69.     }
  70. }