chill-bundles/Command/ChillPersonMoveCommand.php

104 lines
3.5 KiB
PHP

<?php
namespace Chill\PersonBundle\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
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 Chill\PersonBundle\Actions\Remove\PersonMove;
use Doctrine\ORM\EntityManagerInterface;
use Chill\PersonBundle\Entity\Person;
use Symfony\Component\Console\Exception\RuntimeException;
class ChillPersonMoveCommand extends ContainerAwareCommand
{
/**
*
* @var PersonMove
*/
protected $mover;
/**
*
* @var EntityManagerInterface
*/
protected $em;
public function __construct(
PersonMove $mover,
EntityManagerInterface $em
) {
parent::__construct('chill:person:move');
$this->mover = $mover;
$this->em = $em;
}
protected function configure()
{
$this
->setName('chill:person:move')
->setDescription('Move all the associated entities on a "from" person to a "to" person and remove the old person')
->addOption('from', 'f', InputOption::VALUE_REQUIRED, "The person id to delete, all associated data will be moved before")
->addOption('to', 't', InputOption::VALUE_REQUIRED, "The person id which will received data")
->addOption('dump-sql', null, InputOption::VALUE_NONE, "dump sql to stdout")
->addOption('force', null, InputOption::VALUE_NONE, "execute sql instead of dumping it")
;
}
protected function interact(InputInterface $input, OutputInterface $output)
{
if (FALSE === ($input->hasOption('dump-sql') || $input->hasOption('force'))) {
$msg = "You must use \"--dump-sql\" or \"--force\"";
throw new RuntimeException($msg);
}
foreach (["from", "to"] as $name) {
if (empty($input->getOption($name))) {
throw new RuntimeException("You must set a \"$name\" option");
}
$id = $input->getOption($name);
if (\ctype_digit($id) === FALSE) {
throw new RuntimeException("The id in \"$name\" field does not contains "
. "only digits: $id");
}
}
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$repository = $this->em->getRepository(Person::class);
$from = $repository->find($input->getOption('from'));
$to = $repository->find($input->getOption('to'));
if ($from === NULL) {
throw new RuntimeException(sprintf("Person \"from\" with id %d not found", $input->getOption('from')));
}
if ($to === NULL) {
throw new RuntimeException(sprintf("Person \"to\" with id %d not found", $input->getOption('to')));
}
$sqls = $this->mover->getSQL($from, $to);
if ($input->getOption('dump-sql')) {
foreach($sqls as $sql) {
$output->writeln($sql);
}
} else {
$connection = $this->em->getConnection();
$connection->beginTransaction();
foreach($sqls as $sql) {
if ($output->isVerbose()) {
$output->writeln($sql);
}
$connection->executeQuery($sql);
}
$connection->commit();
}
}
}