<?php
namespace App\Commands;
use Doctrine\DBAL\DriverManager;
use Doctrine\ORM\EntityManagerInterface;
use Exception;
use InvalidArgumentException;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\HttpKernel\KernelInterface;
class DBImportCommand extends Command
{
/** KernelInterface $appKernel */
protected static $defaultName = 'flexx:database:import';
private $appKernel;
private $entityManager;
public function __construct(
$name = null, // removed string type-hint
KernelInterface $appKernel,
EntityManagerInterface $entityManager
)
{
$this->appKernel = $appKernel;
$this->entityManager = $entityManager;
parent::__construct($name);
}
/**
* {@inheritDoc}
*/
protected function configure()
{
$this->setDescription('Prepare the database');
$this->addArgument('file', InputArgument::REQUIRED, 'Which file to import');
}
/**
* {@inheritDoc}
*/
protected function execute(InputInterface $input, OutputInterface $output): int
{
// Import SQL File
$path = $this->appKernel->getProjectDir();
$fileName = $path . DIRECTORY_SEPARATOR . $input->getArgument('file');
$db = $this->entityManager->getConnection()->getWrappedConnection();
if(file_exists($fileName)){
$sql = trim(file_get_contents($fileName));
if($sql !== '' && $sql !== '0'){
$db->beginTransaction();
try{
$querySet = $db->prepare($sql);
$querySet->execute();
/*
while($querySet->nextRowSet()){
++$count;
}*/
}catch(Exception $e){
$db->rollBack();
throw $e;
}
}else{
throw new Exception("File {$fileName} appears to be empty.");
}
}else{
throw new Exception("File '{$fileName}' not found.");
}
return Command::SUCCESS;
}
}