Completed
Push — master ( a4c720...062952 )
by Guillaume
02:44
created

GenererDataTestCommand::configure()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 6
nc 1
nop 0
1
<?php
2
3
namespace Starkerxp\StructureBundle\Command;
4
5
6
use Symfony\Component\Yaml\Yaml;
7
8
/**
9
 * Class GenererDataTestCommand
10
 */
11
class GenererDataTestCommand extends AbstractCommand
12
{
13
    public function nomBaseDeDonnee()
14
    {
15
        return $this->getContainer()->getParameter("database_name");
16
    }
17
18
    public function traitement()
19
    {
20
        if ($this->getContainer()->get('kernel')->getEnvironment() == 'prod') {
21
            $this->output->writeln("<error>Cette commande ne peut être lancé en environnement de production</error>");
22
            exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method traitement() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
23
        }
24
        $meta = $this->getEntityManager()->getMetadataFactory()->getAllMetadata();
25
        // On récupère la liste des entites en fonction des nom de tables supposés.
26
        $namespaces = [];
27
        foreach ($meta as $m) {
28
            if ($m->isMappedSuperclass) {
29
                continue;
30
            }
31
            if (count($m->subClasses)) {
32
                $namespaces[$m->getName()] = [
33
                    'nomTable' => $m->getTableName(),
34
                ];
35
                continue;
36
            }
37
            //echo "\n\nOn format\n";
38
            $listeDesColonnes = array_flip($m->columnNames);
39
            $listeDesChamps = [];
40
            foreach ($listeDesColonnes as $column => $field) {
41
                $listeDesChamps[$column] = [
42
                    'field' => $field,
43
                    'type'  => $m->getFieldMapping($field)['type'],
44
                ];
45
            }
46
            $mapping = $m->getAssociationMappings();
47
            foreach ($mapping as $clefJointure => $detail) {
48
                if (!array_key_exists("sourceToTargetKeyColumns", $detail)) {
49
                    continue;
50
                }
51
                $column = array_keys($detail['sourceToTargetKeyColumns'])[0];
52
                $listeDesChamps[$column] = [
53
                    'field'                    => $detail['fieldName'],
54
                    'type'                     => 'integer',
55
                    'sourceToTargetKeyColumns' => $detail['sourceToTargetKeyColumns'][$column],
56
                    'targetEntity'             => $detail['targetEntity'],
57
                ];
58
            }
59
            $namespaces[$m->getName()] = [
60
                'nomTable'            => $m->getTableName(),
61
                'listeDesChamps'      => $listeDesChamps,
62
                'discriminatorValue'  => $m->discriminatorValue,
63
                'discriminatorColumn' => !empty($m->discriminatorValue) ? $m->discriminatorColumn['name'] : null,
64
            ];
65
        }
66
        ksort($namespaces);
67
        $contenu = "";
68
        foreach ($namespaces as $namespace => $data) {
69
            if (empty($data['listeDesChamps'])) {
70
                continue;
71
            }
72
            $export = [];
73
            $listeDesChamps = $data['listeDesChamps'];
74
            $nomTable = $data['nomTable'];
75
            $where = (!empty($data['discriminatorValue']) ? $data['discriminatorColumn']."='".$data['discriminatorValue']."'" : "1=1");
76
            $resultats = $this->getConnection()->fetchAll("SELECT ".implode(",", array_keys($listeDesChamps))." FROM ".$nomTable." WHERE ".$where);
77
            if (empty($resultats)) {
78
                continue;
79
            }
80
            foreach ($resultats as $key => $row) {
81
                $dataExport = [];
82
                foreach ($row as $element => $value) {
83
                    if ($element == 'id') {
84
                        continue;
85
                    }
86
                    $field = $listeDesChamps[$element]['field'];
87
                    if (!empty($listeDesChamps[$element]['targetEntity'])) {
88
                        $value = empty($value) ? null : strtolower("@".$namespaces[$listeDesChamps[$element]['targetEntity']]['nomTable'])."_".$value;
89
                        $dataExport[$listeDesChamps[$element]['field']] = $value;
90
                        continue;
91
                    }
92
                    $dataExport[$field] = $this->formatValue($listeDesChamps[$element]['type'], $value);
93
                }
94
                $export[strtolower($nomTable).'_'.$row['id']] = $dataExport;
95
            }
96
            $contenu .= Yaml::dump([$namespace => $export,], 2, 4)."\n";
97
        }
98
        echo $contenu;
99
    }
100
101
    public function formatValue($type, $value)
102
    {
103
        if (in_array($type, ['datetime', 'date']) && !empty($value)) {
104
            return $value = '<(new \DateTime("'.$value.'"))>';
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $value. This often makes code more readable.
Loading history...
Unused Code introduced by
$value is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
105
        }
106
        if (in_array($type, ['json_array'])) {
107
            return json_decode($value, true);
108
        }
109
        if (in_array($type, ['array'])) {
110
            return unserialize($value);
111
        }
112
113
        return $value;
114
    }
115
116
    protected function configure()
117
    {
118
        parent::configure();
119
        $this->setName('starkerxp:dump-database')
120
            ->setDescription("Exporte une base de données de 'dev' en fixtures yml.")
121
            ->setHelp(
122
                "Cette commande est là pour réaliser un fichier yml destiné aux tests fonctionnels via phpunit couplé avec nelmio/alice.
123
On peut donc aisément recréer l'environnement souhaité avant le lancement des tests unitaires.
124
Attention !!! Cette commande n'est pas destiné à fonctionner sur un gros volume de données."
125
            );
126
    }
127
}
0 ignored issues
show
Coding Style introduced by
As per coding style, files should not end with a newline character.

This check marks files that end in a newline character, i.e. an empy line.

Loading history...
128