1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Chubbyphp\Model\Doctrine\DBAL\Command; |
6
|
|
|
|
7
|
|
|
use Doctrine\Common\Util\Debug; |
8
|
|
|
use Doctrine\DBAL\Connection; |
9
|
|
|
use Symfony\Component\Console\Input\InputInterface; |
10
|
|
|
use Symfony\Component\Console\Output\OutputInterface; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* (c) <http://www.doctrine-project.org>. |
14
|
|
|
*/ |
15
|
|
|
final class RunSqlCommand |
16
|
|
|
{ |
17
|
|
|
/** |
18
|
|
|
* @var Connection |
19
|
|
|
*/ |
20
|
|
|
private $connection; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @param Connection $connection |
24
|
|
|
*/ |
25
|
|
|
public function __construct(Connection $connection) |
26
|
|
|
{ |
27
|
|
|
$this->connection = $connection; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @param InputInterface $input |
32
|
|
|
* @param OutputInterface $output |
33
|
|
|
* |
34
|
|
|
* @return int|null |
35
|
|
|
*/ |
36
|
|
|
public function __invoke(InputInterface $input, OutputInterface $output) |
37
|
|
|
{ |
38
|
|
|
$sql = $this->getSql($input); |
39
|
|
|
$depth = $this->getDepth($input); |
40
|
|
|
|
41
|
|
|
if (stripos($sql, 'select') === 0) { |
42
|
|
|
$resultSet = $this->connection->fetchAll($sql); |
43
|
|
|
} else { |
44
|
|
|
$resultSet = $this->connection->executeUpdate($sql); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
$message = Debug::dump($resultSet, (int) $depth, true, false); |
48
|
|
|
|
49
|
|
|
$output->write($message); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
/** |
53
|
|
|
* @param InputInterface $input |
54
|
|
|
* |
55
|
|
|
* @return string |
56
|
|
|
*/ |
57
|
|
|
private function getSql(InputInterface $input): string |
58
|
|
|
{ |
59
|
|
|
if (($sql = $input->getArgument('sql')) === null) { |
60
|
|
|
throw new \RuntimeException("Argument 'SQL' is required in order to execute this command correctly."); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
return $sql; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* @param InputInterface $input |
68
|
|
|
* |
69
|
|
|
* @return int |
70
|
|
|
*/ |
71
|
|
|
private function getDepth(InputInterface $input): int |
72
|
|
|
{ |
73
|
|
|
$depth = $input->getOption('depth'); |
74
|
|
|
|
75
|
|
|
if (!is_numeric($depth)) { |
76
|
|
|
throw new \LogicException("Option 'depth' must contains an integer value"); |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
return (int) $depth; |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|