1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Shapin\Datagen\Bridge\Symfony\Bundle\Command; |
6
|
|
|
|
7
|
|
|
use Shapin\Datagen\DBAL\Loader\FixtureLoader; |
8
|
|
|
use Doctrine\DBAL\Connection; |
9
|
|
|
use Symfony\Component\Console\Command\Command; |
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\Console\Style\SymfonyStyle; |
14
|
|
|
|
15
|
|
|
class DBALFixturesLoadCommand extends Command |
16
|
|
|
{ |
17
|
|
|
private $connection; |
18
|
|
|
private $groups; |
19
|
|
|
|
20
|
1 |
|
public function __construct(Connection $connection, array $groups) |
21
|
|
|
{ |
22
|
1 |
|
$this->connection = $connection; |
23
|
1 |
|
$this->groups = $groups; |
24
|
|
|
|
25
|
1 |
|
parent::__construct(); |
26
|
1 |
|
} |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* {@inheritdoc} |
30
|
|
|
*/ |
31
|
1 |
|
protected function configure() |
32
|
|
|
{ |
33
|
|
|
$this |
34
|
1 |
|
->setName('datagen:dbal:fixtures:load') |
35
|
1 |
|
->setDescription('Load fixtures in database using DBAL.') |
36
|
1 |
|
->addOption('groups', 'g', InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Which groups should be loaded? (default: all)') |
37
|
|
|
; |
38
|
1 |
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* {@inheritdoc} |
42
|
|
|
*/ |
43
|
1 |
|
protected function execute(InputInterface $input, OutputInterface $output) |
44
|
|
|
{ |
45
|
1 |
|
$io = new SymfonyStyle($input, $output); |
46
|
1 |
|
$io->title('Load fixtures in database using DBAL.'); |
47
|
|
|
|
48
|
1 |
|
$groups = $this->groups; |
49
|
1 |
View Code Duplication |
if ([] !== $wantedGroups = $input->getOption('groups')) { |
|
|
|
|
50
|
|
|
$groups = []; |
51
|
|
|
foreach ($wantedGroups as $wantedGroup) { |
|
|
|
|
52
|
|
|
if (!array_key_exists($wantedGroup, $this->groups)) { |
53
|
|
|
throw new \InvalidArgumentException(sprintf('Unknown group "%s". Available: ["%s"]', $wantedGroup, implode('", "', array_keys($this->groups)))); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
$groups[$wantedGroup] = $this->groups[$wantedGroup]; |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|
60
|
1 |
|
$fixtureLoader = new FixtureLoader(); |
61
|
1 |
|
foreach ($groups as $name => $path) { |
62
|
1 |
|
$fixtureLoader->load($path); |
63
|
|
|
} |
64
|
|
|
|
65
|
1 |
|
foreach ($fixtureLoader->getFixtures() as $fixture) { |
66
|
1 |
|
$this->connection->insert($fixture[0], $fixture[1]); |
67
|
|
|
} |
68
|
|
|
|
69
|
1 |
|
$io->success('Fixtures created successfully.'); |
70
|
1 |
|
} |
71
|
|
|
} |
72
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.